is category child? (6 posts)

  1. echstudios
    Posted 6 years ago #

    How do I write a conditional statement that tests whether a category is a child of a category. My parent category is "Questions" with a bunch of children categories.

    Using is_category('questions') only works at the parent level, but not at the child level.


  2. Shane G
    Posted 6 years ago #


    YOu need to use os_child function to check the child category or you can use an plugin to check the category is child or not..


    Shane G.

  3. MichaelH
    Posted 6 years ago #

    Where, meaning, what template (single.php, category.php, index.php) are you testing this in?

    Or are you trying to do this test in a post loop?

  4. echstudios
    Posted 6 years ago #

    I need to use it in the header.php file to handle the active page highlight for my navigation bar.


  5. echstudios
    Posted 6 years ago #

    I figured I should just post my code so you can see what I mean if that will help.

    <ul class="nav-bar">
    			<li <?php if ( is_home() ) { echo ' class="current"'; } ?>><a href="<?php echo get_option('home'); ?>">HOME</a></li>
    			<li <?php if ( is_category('questions') ) { echo ' class="current"'; } ?>><a href="/rathers">QUESTIONS</a></li>
    			<li <?php if ( is_page('tags') ) { echo ' class="current"'; } ?>><a href="/tags">TAGS</a></li>
    			<li <?php if ( is_page('store') ) { echo ' class="current"'; } ?>><a href="/store">STORE</a></li>
    			<li <?php if ( is_page('submit') ) { echo ' class="current"'; } ?>><a href="/submit">SUBMIT</a></li>
    			<li <?php if ( is_page('about') ) { echo ' class="current"'; } ?>><a href="/about">ABOUT</a></li>
    			<li <?php if ( is_category('blog') ) { echo ' class="current"'; } ?>><a href="/blog">BLOG</a></li>

    It basically just changes the css class based on which page its on. So it works when I view the "Questions" category archive, but not when I view an actual post within the subcategories. I know I could just manually add all my subcategories as a conditional statement, but I have many so I'd like to find a cleaner way to handle this. Also, my blog is set up as its own category which also has the same problem.

    Thanks again!

  6. MichaelH
    Posted 6 years ago #

    There is the cat_is_ancestor_of function but that could return true if a category was a grandchild of another category. Try this:

    // in category template, test if queried category is child of another category
    if ( is_category() ) {
    $parent = 8;
    $categories = get_categories('include='.get_query_var('cat'));
    if ( $categories[0]->category_parent == $parent ) {
    echo 'category ' . $categories[0]->name . ' is a child of category ' . $parent;

Topic Closed

This topic has been closed to new replies.

About this Topic