1

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?

1 Answer 1

1

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.

1
  • Awesome! I was thinking along the lines of this. But you nailed it! Thanks!
    – dmarges
    Nov 2, 2012 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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