How to get parent category name in WordPress template? And can I fulfill the request by the parent category?

I tried to get help on the WordPress forums, but no luck. Anyway, here is my question ...

Suppose I create 10 parent categories and 2 subcategories for each parent. My WordPress post belongs to one subcategory of a specific parent category

How to get ONLY the parent category? I do not need subcategory names? What WordPress code will do this?

And one more question...

Is it possible to request post by the parent of a subcategory using:

but instead of entering cat=1 or the name of a specific category, I can do something like:

Thus, it automatically inserts and requests post for the parent of any particular subcategory that it clicked on?

+4
source share
4 answers

To get the name of the parent category, use the get_cat_name() function, and the parent parameter like this:

 $cat = get_the_category(); $parentCatName = get_cat_name($cat[0]->parent); 
+3
source

All of these answers failed for me.

I eventually managed to display the name of the topmost category after this:

  $categories = get_the_category(); $category= ''; foreach($categories as $childcat) { $parentcat = $childcat->category_parent; if($parentcat>0){ $category = get_cat_name($parentcat); continue; } } $category = (strlen($category)>0)? $category : $categories[0]->cat_name; 
+3
source

Found this answer that gives you the first prototype of the ancestor. It can be easily changed to give you a name.

Got it here: http://nick.boldison.com/wordpress/wordpress-get-top-level-parent-category/

 <?php // get parent category slug $parentCatList = get_category_parents($cat,false,','); $parentCatListArray = split(",",$parentCatList); $topParentName = $parentCatListArray[0]; $sdacReplace = array(" " => "-", "(" => "", ")" => ""); $topParent = strtolower(strtr($topParentName,$sdacReplace)); ?> 

In fact, to get the parent name:

 // get parent category slug $parentCatList = get_category_parents($cat,false,','); $parentCatListArray = split(",",$parentCatList); $topParentName = $parentCatListArray[0]; 
+1
source

Many answers and examples in Wordpress docs:

get parent categories

get category

(And it looks like some code snippets or other text did not fall into your original question)

-1
source

All Articles