get_single_cat()

2010-01-16 @ 14:52

The problem

WordPress have a built in function called get_the_category(). Because the possibility to have posts in more than one category, it returns an array.

$category = get_the_category();
echo $category[0]->cat_name;

The result of the function is inserted into an array. It then echos the first category title. The code is not as short and easy as it could be.

The solution

I created a function that returns a value depending of the input type. Put the function into your functions.php in your theme folder.

function get_single_cat($type = 'ID')
{
     $category = get_the_category();

     switch ($type)
     {
          case 'ID':
               return $category[0]->cat_ID;
               break;
          case 'title':
               return $category[0]->cat_name;
               break;
          case 'name':
               return $category[0]->category_nicename;
               break;
          case 'description':
               return $category[0]->category_description;
               break;
          case 'parent':
               return $category[0]->category_parent;
               break;
          case 'count':
               return $category[0]->category_count;
               break;
          default:
               return;
     }
}

The function call

Call the function inside the post loop somewhere in your theme. The example below prints out all the current category information.

echo get_single_cat();
echo get_single_cat('ID');
echo get_single_cat('title');
echo get_single_cat('name');
echo get_single_cat('description');
echo get_single_cat('parent');
echo get_single_cat('count');

If the input type is not sent it will return the category ID, as default.

Improvements

Do you have any ideas, bugs, features or anything else to improve the code? Write a comment and I’ll look into it.

Share
RSS-feed for comments

3 replys to “get_single_cat()”

  • patrick »
    2011-03-09 @ 5:15 f m

    thanks jen , its work for me , i have try it at my categorie page

  • vb078
    2013-08-16 @ 1:38 e m

    Hello :)
    I would like to make it with links (linked cat name), It’s possible?
    Optionaly can you help with child cat names? (not single)

    Thank you so much
    (adding display-posts-shortcode categories)

  • vb078
    2013-08-16 @ 1:45 e m

    quick finding a solution for linking get_category_link(get_single_cat(‘ID’))
    maybe you have some best one ?!

    I searching for multiple category display in the loop right now :)

    Thx you for reading me !

Leave a reply