WordPress.org

Ready to get started?Download WordPress

Forums

How to get top most parent category id. (4 posts)

  1. Roopesh Jain
    Member
    Posted 3 years ago #

    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

  2. DianeV
    Member
    Posted 3 years ago #

    Thanks. Awfully kind of you. :)

  3. Arun Singh
    Member
    Posted 2 years ago #

    it will work for 2 level only...

  4. Arun Singh
    Member
    Posted 2 years ago #

    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;
    }

Topic Closed

This topic has been closed to new replies.

About this Topic