Get Top Level Parent Category Id Of a Single Post

PHP

Get the top level parent category ID of the single post being viewed on single.php. Works on single.php.

Step 1

Requires this function. Place it in your functions.php or other function file.\

/**
* Returns ID of top-level parent category, or current category if you are viewing a top-level
*
* @param    string      $catid      Category ID to be checked
* @return   string      $catParent  ID of top-level parent category
*/
function smart_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;
}

Step 2 – Usage

Use this in single.php to get the category id of the top level parent category.

// get the top level cat id of a single post
 
$category = get_the_category($post->ID);
 
$catid = $category[0]->cat_ID;
 
$top_level_cat = smart_category_top_parent_id ($catid);

 

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *