Earlier, you saw how category-specific classes are added to the body tag and the individual post. With category archives, you can customize your category display even further. For example, I often use the_excerpt() on most category archives to provide a quick overview my readers can easily skim.

However, in some situations, like a podcast category, you want the archive to look just like a complete blog home page. In that case, you duplicate category.php and call it category-podcast.php. You then alter category.php to use the_excerpt() while keeping the_content() in the podcast category. You can also use the conditionals again (in_category()) to include podcast-specific information in your sidebar: schedules, donation links, etc.

Category archives have a little quirk: if you're looking at a category that has subcategories, posts from those subcategories will be mixed in with the posts from the parent category. Listing 6-23 shows a category archive template that first lists the child categories, then shows the posts assigned only to the parent category using the in_category() conditional.

Listing 6-23. Listing subcategories and limiting the loop to the parent category

<h2 class="pagetitle"><?php single_cat_title(); ?></h2> <?php

<ul class="subcategories">

<?php $cats = get_categories('order=desc&title_li=&child_of='.$catid); foreach ($cats as $cat) { ?> <li>

<h4><a href="<?php echo get_category_link( $cat->cat_ID ); ?>" rel="bookmark" title="<?php echo $cat->cat_name; ?>"><?php echo $cat->cat_name; ?></a></h4> </li>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php if (in_category($catid) ) : ?>

<h2 <?php post_class(); ?>><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

<?php the_content(); ?> <?php endif; endwhile; ?>

Here, you use the get_query_var() function to find out which category you're looking at. You can use this function to retrieve any of the variables that make up the invisible Loop query, but since you know you're working with a category archive, it's the category ID you're interested in.

Once you have the ID, you can use get_categories() to print a list of all the current category's subcategories. Then you can go into your typical Loop, but you've added a conditional tag (which is discussed later in this chapter) to print the title and content only if the post is in the parent category, not any of its subcategories.

Was this article helpful?

0 0

Post a comment