5
votes

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?

4
There seems to be some text missing from your post.JohnK

4 Answers

5
votes

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);
3
votes

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;
1
votes

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];
-1
votes

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)