Tag Archive for 'programming'

[WordPress Tip] How to exclude children categories on a template

Yesterday I came across a problem while trying to get WordPress to show me only posts from the top level category without showing posts under sub-categories.

Let’s say I had a Category named Notebooks and under it there were Hewlett-Packard, Acer and Lenovo. Now what I wanted to do was to only display the posts that I published under Notebooks and not under Acer.

By default WordPress will show you the posts you published under Notebooks AND under Acer AND under Hewlett-Packard AND Lenovo, as if they were all posted under the same category (when I head to Hewlett-Packerd it will only show me posts under that category, of course).

After tens of hours of research (yeah), I found the function that could make my dream come true: is_category()

That function shows posts only from the category specified and NO OTHER ONE.

So if you want to modify a template to display posts only from the category you are calling and not display the posts from children categories (sub-categories), just change this:

<?php while (have_posts()) : the_post(); ?>

to this:

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

Then you have to change your endwhile:

<?php endwhile; ?>

to

<?php } endwhile; ?>

There were no direct answers to my problem on the WordPress Codex or anywhere else (that I could find).

A complete example:

<?php get_header(); ?>

<?php if (have_posts()) : ?>

<div class=”post”>

<h1><?php single_cat_title(); ?></h1>

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

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

<?php } endwhile; ?>

</div>

<?php else : ?>

<div class=”post”>

<h2>Not Found</h2>
<p class=”center”>Sorry, but you are looking for something that isn’t here.</p>
<center><?php include (TEMPLATEPATH . “/searchform.php”); ?></center>

</div>

<?php endif; ?>

</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

This was done using WordPress 2.6.5