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


Thanx a lot for the share. I have follow your tip and now I have something like :
have_posts()) : $recent->the_post();
if (in_category(‘fil-shopping’)) {
//do something
} endwhile; ?>
in_category() is a perfect function for this case.
hummm the textarea loose some php code on my previous comment.
So my query is :
have_posts()) : $ recent->the_post()
if (in_category('$catname')) {
//do something
} endwhile;
?>
Thank you, I’ve been searching for this and only found other examples where I had to know the cat id, but like you I really needed the code in the template without having to worry about the id. This snippet works great with themes that have a drop down category menu.
I think the admin of this web site is really working hard
in support of his site, because here every material is quality based
stuff.
My web page; 19 Inch lcd tv