Recently, I worked on a WordPress-powered site that required the category pages to show links to the first level of subcategories and the posts filed in the category but not the subcategories themselves.
I couldn’t find any adequate documentation, so I’m putting this here for posterity:
For listing the Subcategories, WordPress has a function wp_list_categories
.
This code gets the first-level children of the current Category:
wp_list_categories(array(
'depth' => 1,
'child_of' => get_category($cat)->cat_ID);
));
The function get_posts
is curious: if a category is specified, it gets all posts that are filed under that category and all subcategories.
$posts = get_posts(array( 'cat' => get_category($cat)->cat_ID );
To get around this problem, a simple if
case can be put into the loop:
foreach( $posts as $post ) {
$cats = get_the_category($post->ID);
if ( $cats[0].term_id == get_category($cat)->cat_ID ) {
echo "<a href=\";" the_permalink(); echo "\">"; the_title(); echo "</a>";
}
}
Of course, if you have more than one category, you can use a nested foreach:
foreach( $posts as $post ) {
$in_cat = false;
$cats = get_the_category($post->ID);
foreach ( $cats as $cat ) {
if ( $cat->term_id == get_category($cat)->cat_ID ) {
$in_cat = true;
break;
}
}
if ( $in_cat ) {
echo "<a href=\";" the_permalink(); echo "\">"; the_title(); echo "</a>";
}
}
And that’s all there is to it.