WordPress function like is_category for subcategory? is_subcategory?

Is there a function in WordPress that will check if the page you are on is a sub-category archive page?

Like the way is_category checks if it’s a category page?

Related posts

Leave a Reply

2 comments

  1. Sub-categories use the regular category archive page by default. There is no function such as is_subcategory. But you can write your own.

    Here is an example:
    This will check if the current page is a sub-category. Or if you pass an ID it will check if the ID is a subcategory.

    function is_subcategory( $cat_id = NULL ) {
    
            if ( !$cat_id )
                $cat_id = get_query_var( 'cat' );
    
            if ( $cat_id ) {
    
                $cat = get_category( $cat_id );
                if ( $cat->category_parent > 0 )
                    return true;
            }
    
            return false;
        }
    
  2. If you want to check the current location (without the need to specify an ID):

    // Return type - Boolean or Object (if the latter, then check the result with is_object)
    function is_subcategory($return_boolean=true) {
        $result = false;
        if (is_category()) {
            $this_category = get_queried_object();
            if (0 != $this_category->parent) // Category has a parent
                $result = $return_boolean ? true : $this_category;
        }
        return $result;
    }