3

How can I detect whether current page is a product sub category page?

I've tried with the following but it will always print out "NO"

function is_subcategory($category = null) {
    if (is_category()) {
        if (null != $category){
            $cat = get_category($category);
        }else{
            $cat = get_category(get_query_var('cat'),false);
        }
        if ($cat->parent == 0 ){
            return false;
        }else{
            return true;
        }
    }
    return false;
}

if (is_subcategory()){
    echo "YES";
}else{
    echo "NO";
}
2
  • Uhm yes, or atleast on frontend im looking at a product overview for a subcategory. The code itself is added to header.php right after <?php wp_head(); ?> May 10, 2016 at 15:31
  • is_category works for in built category not the product custom taxonomy!
    – Sumit
    May 10, 2016 at 16:00

1 Answer 1

6

is_category() only check the built in post category. Product categories are custom taxonomies. So you need to use is_tax() instead of is_category() and get_term() instead of get_category().

Check this example:-

function is_subcategory($cat_id = null) {
    if (is_tax('product_cat')) {

        if (empty($cat_id)){
            $cat_id = get_queried_object_id();
        }

        $cat = get_term(get_queried_object_id(), 'product_cat');
        if ( empty($cat->parent) ){
            return false;
        }else{
            return true;
        }
    }
    return false;
}

Also safe side instead of get_query_var() use get_queried_object_id()

4
  • Great and clean answer. Is $cat->parent == 0 safe to use? I've always used $cat->parent == ''.
    – N00b
    May 10, 2016 at 17:07
  • Thank you! Well AFAIK with == 0 and '' same thing. What do you say ?
    – Sumit
    May 10, 2016 at 17:09
  • Yup, both usually means false. I was just thinking (should not think too much) that maybe there are some edge cases with WordPress. I guess now I know better.
    – N00b
    May 10, 2016 at 17:12
  • Okay. But I always relay on empty(). Perhaps I should edit my answer. Thanks :)
    – Sumit
    May 10, 2016 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.