October 31st in Wordpress by .

How to get parent category name in WordPress?

In wordpress, sometimes you may have many subcategories for a different parent categories. By default wordpress lists all sub-categories.

if i have category structure like

Drupal
- 2 Column
- 3 Column
- Left sidebar
- Right sidebar

WordPress
- Fixed Width
- Widget Ready
- News/Magazine
- Photogallery

and if i do a wordpress post (with title say CSS Gallery) inside WordPress -> Photogallery i want the title to display

Blog Title > Parent Category Name > Blogpost Title
like
Top Best Themes > WordPress > CSS Gallery

Here is the wordpress code to display parent category name. Its a very simple code but did the job for me. You can insert inside header.php if you want to change titles in wordpress. This is how it works. First it gets the category name of wordpress post, and from it gets the Category ID of its parent then it gets the parent name with get_cat_name() function. If the parent is empty (which means the wordpress post is already listed in the parent category) then print the current category name.

<?php
$category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
if (!empty($parent)) {
echo '&raquo; ' . $parent;
} else {
echo '&raquo; ' . $category[0]->cat_name;
}
?>

Note that this code has a limitation and it works best with only one level deep.!

Similar Posts:

19 Comments

  • Alfie
    March 15, 2009
  • Zigzo
    May 27, 2009
  • max
    May 30, 2009
  • Antonio S
    June 10, 2009
  • timur senga
    June 17, 2009
  • Sven
    November 9, 2009
  • kzok
    January 12, 2010
  • moezzig
    March 17, 2010
  • Steve
    April 6, 2010
  • gerry
    April 23, 2010
  • Caroline Bryant
    May 20, 2010
  • Ashok
    June 2, 2010
  • Erin Turner
    July 28, 2010
  • Encryption Softwares :
    October 25, 2010
  • Granite Tiles ·
    November 10, 2010
  • donya
    December 10, 2010
  • fanny
    July 16, 2011
  • marky6
    October 10, 2011
  • Héctor Omar
    October 13, 2011

Leave A Comment.