Support » Fixing WordPress » How to get top most parent category id.

  • Hello All,

    Here is the code for find the top most parent category from the current category or which category you want.

    ***********************************************************************
    Copy and paste below code in function.php file in your wordpress theme directory.
    ***********************************************************************
    function get_top_parent_category($cat_ID)
    {
    $cat = get_category( $cat_ID );
    $new_cat_id = $cat->category_parent;

    if($new_cat_id != “0”)
    {
    return (get_top_parent_category($new_cat_id));
    }
    return $cat_ID;
    }
    ***********************************************************************
    Copy and paste above code in function.php file in your wordpress theme directory.
    ***********************************************************************

    then call this function where you want.

    $cat_ID = get_query_var(‘cat’);

    if(get_top_parent_category($cat_ID)==3) //3 is the top most parent category id //
    {
    //***************Your Code here*************//
    }

    Thankyou All

    Roopesh Jain

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thanks. Awfully kind of you. 🙂

    it will work for 2 level only…

    try this to get the top most category for any depth level

    function get_top_parent($cat){
    $curr_cat = get_category_parents($cat, false, '/' ,true);
    $curr_cat = explode('/',$curr_cat);
    $idObj = get_category_by_slug($curr_cat[0]);
    echo  $id = $idObj->term_id;
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How to get top most parent category id.’ is closed to new replies.