Currently Browsing: Home » WordPress Categories

WordPress Categories

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.

This entry was posted on Thursday, April 16th, 2009 at 05:00:39. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.