How do I check If sub category of category x in WordPress?

Is there a way that I can check using a conditional whether the page is a subcategory of a specific category ?

i.e: on my ‘category.php’ I currently have:

Read More
 <?php } else if (is_category( 'blog' )) { ?>

This is to render a different view depending which category page the user is on.

Is it possible to do something like ?

 <?php } else if (is_sub_category_of( 'blog' )) { ?>

Related posts

Leave a Reply

3 comments

  1. Although very old, I’ve created the perfect solution.

    Add this to your functions.php file:

    /** check if the current category is a child of a given category **/
    function current_cat_is_sub_of($parent = ''){
        global $wp_query;
        $cat = $wp_query->get_queried_object();
    
        if ( ! isset( $wp_query ) ) {
            _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
            return false;
        }
        elseif( $cat->parent!=0 && $cat->parent == $parent ){
            return true;
        }
        else{
            return false;
        }
    }
    

    Then you can use it various ways. For example to change the displaying order of posts in all subcategory pages under a given category:

    /** order posts under category 123 from new to old **/
    function order_digital_posts($query){
        if (current_cat_is_sub_of('THE PARENT CATEGORY ID') && $query->is_main_query()) {
            $query->set( 'order', 'ASC' );
        }
    }
    add_action('pre_get_posts', 'order_digital_posts');
    

    Enjoy!
    Itamar

  2. Old question, but I stumbled on this last night and I had to find an answer for myself.

    This is on my category.php page:

    $category = get_the_category();
    
    if(isset($category[1]) && $category[1]->slug === 'catagory-you-want') {
    
        // Do stuff if it's a child of "Category You Want"
        // You can use $category[1]->cat_ID to check which category instead
    
    }
    

    The current subcategory is in $category at position 0.

    This would be harder if “Category You Want” had a parent category and you didn’t know it.

  3. You can see if your current category parent id matches the “blog” category id. If so, your current category is a subcategory of “blog”.

    $current_cat = get_query_var("category");
    $cat = get_term_by('slug',$current_cat,"category");
    $blog = get_term_by('slug',"blog","category");
    
    
    if($cat->parent == $blog->ID){ /*your code */ }
    

    This code will do the functionality you described.