Reputation: 151
Wordpress - How To Get Parent Category ID
my category is
news
---->sport news
i have a post in sport news.
how to get the parent(news) id when i go into the post of sport news?
this code echo parent cat name
foreach((get_the_category()) as $childcat) { $parentcat = $childcat->category_parent;
echo get_cat_name($parentcat);
echo $parentcat->term_id;}
echo $post->post_parent->cat_ID;
this code echo single page cat name
global $post;$category = get_the_category($post->ID);echo $category[0]->name;
this chode echo id of cat name
$category = get_the_category(); echo $category[0]->cat_ID;
i need echo parent id (cat_ID) plz help me
thanks.
Upvotes: 15
Views: 66492
Reputation: 1783
I know it is asked a long time ago but because none of the answers worked for me, decided to share what I've done:
$post_id = 1000;
$category = get_category($post_id);
$category_parent_id = $category[0]->parent;
// It gets the name and not the id or the object
$category_name = get_the_category_by_ID($category_parent_id);
// And here is the parent of the category
$category_parent = get_category_by_path($category_name);
Upvotes: 0
Reputation: 6648
For Wordpress 5.9.
Getting parent category id:
$cat = get_queried_object();
$parentCatId = $cat->parent;
Getting current category id:
$cat = get_queried_object();
$catId = $cat->term_id
Getting category name by id:
$name = get_the_category_by_ID($catId);
Upvotes: 1
Reputation: 1
<?php
if (is_category())
{
$thiscat = get_category( get_query_var( 'cat' ) );
$catid = $thiscat->cat_ID;
$parent = $thiscat->category_parent;
if (!empty ($catid) ) {
$catlist = get_categories(
array(
'child_of' => $catid,
'orderby' => 'id',
'order' => 'ASC',
'exclude' => $parent,
'hide_empty' => '0'
) );
?>
<div class="subcat-list">
<ul>
<?php foreach ($catlist as $category) { ?>
<li><a href="<?php echo get_category_link( $category->term_id ); ?>"><?php echo $category->name; ?></a></li>
<?php } ?>
</ul>
</div>
<?php } } ?>
Upvotes: 0
Reputation: 244
$thiscat = get_query_var('cat'); // The id of the current category
$catobject = get_category($thiscat,false); // Get the Category object by the id of current category
$parentcat = $catobject->category_parent; // the id of the parent category
Upvotes: 9
Reputation: 2306
Simply, very simply.
//firstly, load data for your child category
$child = get_category(31);
//from your child category, grab parent ID
$parent = $child->parent;
//load object for parent category
$parent_name = get_category($parent);
//grab a category name
$parent_name = $parent_name->name;
Study get_category
Upvotes: 19