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 44 articles by Satish
6 Comments Post a Comment
  1. Ronny says:

    hey, great function!! I was wondering if there is anyway to exclude categories from being listed?
    Again thanks a lot for the function! it really is great!

  2. Stephanie says:

    Thank you! This came just in time when the higher-ups were asking me if this was possible since some of our posts had a lot of categories attached and thus, messing up the layout. I got it done in 5 minutes after reading this tutorial. :) Good job.

  3. benjamin says:

    I really love this theme, but recently, the swift table seems does’t work well, could you help me ?

  4. 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




Download SWIFT