<?php
global $wp_query;
// If the category name is set for this page...
// (which it will be when viewing a category on the category.php template)
$category_name = $wp_query->get( 'category_name' );
if ( isset( $category_name ) && ! empty( $category_name ) ) {
// Now we have the category name, but we want more so we're going
// to get the full category details using the slug name.
$category_all = get_category_by_slug( $category_name );
// Now that we have all of the category details, we can safely
// extract the category ID.
$category_id = $category_all->cat_ID;
// Using the category ID we just obtained, we can get all the children
// of this category (returned in an array).
$category_children = get_term_children( $category_id, 'category' );
// And now we just need to pass this array of children to exclude
// into $wp_query. We'll use query_posts() for this. Don't forget
// to merge in all of the previous arguments.
query_posts( array_merge( $wp_query->query, array(
'category__not_in' => $category_children
) ) );
}
// Now run your WordPress loop as normal and notice that posts from
// child categories no longer appear when viewing a parent category.
if ( have_posts() ) : while ( have_posts() ) : the_post();
the_title();
the_content();
// Other stuff you do
endwhile;
endif;
// Lastly, you may want to rewind your posts since we used query_posts().
rewind_posts();
?>