get_single_cat()
2010-01-16 @ 14:52The 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.






2011-03-09 @ 5:15 f m
thanks jen , its work for me , i have try it at my categorie page