0

Wordpress provides conditionals like is_home() and is_category(). I'd like a function to tell me if the current context belongs to a category that is a subcategory (so, not a parent).

I tried this, but it returns true on any category (and subcategory) context

function is_subcategory($category) {
    if (is_category()) {
        foreach ($category as $c) {
            if ($c->parent > 0) {
                return true;
            }
        }
        return false;
    }
}
3

try this:

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;
}

Usage:

//to check if the current context is a subcagetory:

if (is_subcategory()){
    //its a subcategory;
}else{
    //nope is aparent category
}

//to check if a specific category is a subcategory pass its ID, eg:
if (is_subcategory(12)){
    //yes category with the id of 12 is a subcategory;
}else{
    //nope is aparent category
}

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.