
Some times as a theme developers we may have to display only specific number of categories a post is filed in as a large number of categories may break the layout in some cases and sometimes we may have to display only one category.
For example in SWIFT magazine layout, I display one category overlayed on the thumbnail.
Unfortunately WordPress functions get_the_category(), the_category() do not take any arguments and display all the categories the post is filed in. I wrote this small function during the development of swift to echo a specific number of categories a post is filed in. I hope this will help the fellow theme developers
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/*
A custom function to echo specified number of categories a
post is filed in.
(Takes number of categories to be displayed as argument)
Written by Satish Gandham
Author URL: http://swiftthemes.com
Contact: http://swiftthemes.com/contact-me/
*/
function swift_list_cats($num){
$temp=get_the_category();
$count=count($temp);// Getting the total number of categories the post is filed in.
for($i=0;$i<$num&&$i<$count;$i++){
//Formatting our output.
$cat_string.='<a href="'.get_category_link( $temp[$i]->cat_ID ).'">'.$temp[$i]->cat_name.'</a>';
if($i!=$num-1&&$i+1<$count)
//Adding a ',' if it's not the last category.
//You can add your own separator here.
$cat_string.=', ';
}
echo $cat_string;
} |
Usage is similar to the_category() function, except we take arguments here.
|
1 |
Filed under <?php swift_list_cats(3); ?> |
If you have any questions feel free to drop them in comments
