How do I get the parent category name in WordPress template? And can I query post by the parent category?

邮差的信 提交于 2020-07-29 06:51:38

问题


I tried getting help on the WordPress forums but no luck. Anyways, here is my question...

Lets say I am creating 10 parent categories and 2 sub categories to each parent. My WordPress post belongs to one sub category of a particular parent category

How do I get the parent category name ONLY? I don't want subcategories names? what WordPress code would do that?

And one more question...

Is it possible to query post by the parent of a sub category by using:

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

So this way it would automatically insert and query post for the parent of any particular sub category that's clicked on?


回答1:


To get the parent category name, use the get_cat_name() function, with the parent as the parameter -- like so:

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



回答2:


All these answers failed for me.

I eventually managed to display a post's topmost category name like 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:


Found this answer, which gives you the first ancestor slug. It could easily be modified to give you the 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];



回答4:


Lots of answers and examples in the Wordpress docs:

get category parents

get the category

(And it looks like some code snips or other text didn't come through in your original question)



来源:https://stackoverflow.com/questions/1228130/how-do-i-get-the-parent-category-name-in-wordpress-template-and-can-i-query-pos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!