Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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;
    }
}
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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
}
share|improve this answer
    
Works beautifully, thanks a lot! –  pixeline Sep 8 '11 at 9:50
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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