Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

44 PART I • Getting Started with WordPress


output within the loop, leaving the actual loop part (as described and defined in Chapter 2)
within the category archive, you have more detailed control and can more easily reuse your
template files. The same type of content output might be used in an author archive, for
example, but the criteria around it might be different. By focusing on the actual output and
including it using get_template_part(), you make things a bit easier on yourself.

Take a look at a category archive, residing in the category.php template file. This is the
complete loop that you want to be using:

<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><a href="<?php the_permalink(); ?>" title="<?php
the_title_attribute(); ?>">
<?php the_title(); ?>
</a></h2>
<?php the_content(); ?>
</div>
<?php endwhile; ?>

The first and last lines are the actual loop, as you’ll recall from Chapter 2, and the code in
between is the output, or content, if you will. Now, you want to be able to reuse the code
within for other loop outputs, or possibly overwrite it with a child theme in the future, so
you’ll store that in its own template file and include it using get_template_part() as
described earlier — like so:

<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'archive' ) ;?>
<?php endwhile; ?>

Then you’ll put the actual output in a file called content-archive.php, which will be included as
specified. You could use this for just category.php, as mentioned earlier, or for other suitable
archive templates as well. For clarity’s sake, here are the contents of content-archive.php:

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><a href="<?php the_permalink(); ?>" title="<?php
the_title_attribute(); ?>">
<?php the_title(); ?>
</a></h2>
<?php the_content(); ?>
</div>

What you have now is two files — category.php, which contains the actual loop (but not its
contents) and whatever other markup is needed to make the category archives of your site
look the way you want, and content-archive.php, which contains the actual output of the loop.
Free download pdf