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

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

Read More

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?

Related posts

Leave a Reply

4 comments

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