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.

Just wondering what the best way to get the top-most level category (grandparent) of a given category assuming it has one?

Example structure:

Operating Systems - Mac - - Mountain Lion - Windows - - Windows XP

I want to be able to somehow get the ID of the "Operating Systems" category from within the Windows XP category.

Any suggestions?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

You could write a simple function to do this each time you need to. Here's an example I found on this website.

function pa_category_top_parent_id( $catid ) {
    while( $catid ) {
        $cat = get_category( $catid ); // get the object for the catid
        $catid = $cat->category_parent; // assign parent ID (if exists) to $catid
        // the while loop will continue whilst there is a $catid
        // when there is no longer a parent $catid will be NULL so we can assign our $catParent
        $catParent = $cat->cat_ID;
    }
    return $catParent;
}

Then you can use this function anywhere like so:

$catid = get_query_var( 'cat' );
echo pa_category_top_parent_id( $catid );

Reading the comments in the code it is pretty self-explanatory. Hope this helps.

share|improve this answer
    
Awesome! I was thinking along the lines of this. But you nailed it! Thanks! –  dmarges Nov 2 '12 at 19: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.