How to Make a Wordpress Category Page Without Showing the Category Children
I recently ran into a problem with the way Wordpress handles categories and subcategories. My wife wanted to add a new section to her real estate website. Her brokerage gave her a large collection of real estate buying guides. The new articles all belonged to categories already, and she already had a section for buying guides.
I decided to make subcategories in her current buying guide section and add the content to the subcategories. I would then make a custom category page using the wordpress category template “category-<cat_id>.php”.
Wordpress uses templates to manage many of the common features on a blog. Categories is a special template that uses a hierarchy to display the category pages. The hierarchy is a follows: category-<cat_id> will override category.php which will override archive.php which will override index.php.
Therefore, I can have a default category page for all the other categories, except for this special category for buying guides.
Read more about category templates here
On the custom category page, I wanted to list the 5 most recent blog posts under the main category “buying guides” and then list all the subcategories and the blog posts in the subcategories.
The problem I ran into was that all children are displayed under a category when using the wordpress function get_posts(’cat_id=x’).
The solution is to use the wordpress function query_posts(array(’category__in’=>array(x))) – NOTE THAT IS A DOUBLE UNDERSCORE
query_posts will also take the argument for cat_id, or category name, but again, it displays all subcategory posts.
//$cat_id = main category id
query_posts(array('category__in' => array($cat_id)));
while (have_posts()) : the_post();
//do something with the main category
endwhile;
Then to get the children, I can do the same with each subcategory
$categories = get_categories('child_of='.$cat_id);
foreach($categories as $c)
{
query_posts(array('category__in' => array($c->term_id)));
while (have_posts()) : the_post();
//do something with the subcategories
endwhile;
{
One Response to “How to Make a Wordpress Category Page Without Showing the Category Children”
Leave a Reply |
Don't be shy, Speak your mindIf you have any questions, concerns or general comments about this post, please leave a comment.
Show us your face by signing up for a FREE Gravatar at Gravatar.com! Don't be a faceless voice in the crowd.
|

u have a usful and nice post.