Modified version of get_the_category to limit the number of categories displayed.


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

/*
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.

Filed under <?php swift_list_cats(3); ?>

If you have any questions feel free to drop them in comments

Subscribe / Share

Article by Satish

Satish Gandham is a self taught web designer and developer. He is the founder of SwiftThemes. You can connect with him on twitter @ Gandham Satish tagged this post with: , , , Read 31 articles by Satish
One Comments Post a Comment
  1. Lynden says:

    Hi there, I love your work, I have had the 4.0 version working nicely on my site, and my seo is working really considering I have only had the site running for 1 month. I will move to 5.0 but found it a little buggy for now so I went back to 4. But great job. I like the java slider :)
    If you want to see my site it is http://www.healthinformatics.info

Leave a Reply




Why are SwiftThemes server friendly..

SwiftTheme's use minumum number of images and minimum number of external files, thus reducing the number of HTTP reqests and thus reducing the load on server. This makes your site load faster.
Need help customizing SWIFT, Check out our support forum.

Support Forum

Testimonials

Thank you very much for having created a wonderful theme! We use Swift on www.narconon.ca/blog with a few modifications. We like it very much! A few weeks after we applied this theme, our visits increased drastically (+more 400 visits/week)!
-Eric