WordPress function to get top level category of a post

How to find the top most category of a post in wordpress?

For example I have categories like this:sub-1.2, sub-2.2, parent-3.

Parent-1
    - sub-1.1
         - sub-1.2
Parent-2
    - sub-2.1
         - sub-2.2
Parent-3
    - sub-3.1
         - sub-3.2

Now I want to get the top most categories like Parent-1,Parent-2, Parent-3.

/**
 * Get Post Ancestor Categories
 *
 * @param int    $post_id Post ID.
 * @param string $format slug or name of the category.
 * @return array
 */
function readnote_get_post_root_category( $post_id, $format = 'slug' ) {
	$taxonomy = 'category';
	$list     = array();
	$terms = get_the_category( $post_id );
	foreach ( $terms as $term ) {
		$parents = get_ancestors( $term->term_taxonomy_id, $taxonomy, 'taxonomy' );
		array_unshift( $parents, $term->term_taxonomy_id );
		$ancestors[] = end( $parents );
	}
	$ancestors = array_merge( array_unique( $ancestors ), array() );
	foreach ( $ancestors as $term_id ) {
		$ancestor = get_term( $term_id, $taxonomy );
		$name     = ( 'slug' === $format ) ? $ancestor->slug : $ancestor->name;
		$list[] = $name;
	}
	return $list;
}

II feel that this solution is quite simple, probably not the best one in terms of efficiency and there may be a better one.

Looking forward to discussing with you.


发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据