How to get grandparent of a given category

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

Example structure:

Read More

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?

Related posts

Leave a Reply

1 comment

  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.