How To – list categories with Images

Image for each category in WordPress in not that hard to achieve and ever since i posted an how to WordPress Category Extra Fields I've been asked over and over how to do that so i decided to post a quick how to .

So assuming that you already have custom fields for your categories and you have set an image url for each category then next thing we have to do is create our get_categories_with_images function:

function get_categories_with_images($post_id,$separator ){
	
	//first get all categories of that post
	$post_categories = wp_get_post_categories( $post_id );
	$cats = array();
	
	foreach($post_categories as $c){
		$cat = get_category( $c );
		$cat_data = get_option("category_$c");
		
		//and then i just display my category image if it exists
		$cat_image = '';
		if (isset($cat_data['img'])){
			$cat_image = '<img src="'.$cat_data['img'].'">';
		}
		$cats[] =  $cat_image . '<a href="'.get_category_link( $c ) . '">' .$cat->name .'</a>';
	}
	return implode($separator , $cats);
}

pretty self explanatory but will go over it just to be sure:

  • On line 4 we get the list of category ids for the categories associated with that post.
  • On lines 7-16 we get the name of each category ,the extra fields for that category and create a link to that category with the category name and Image if one exists for that category.
  • On line 18 we return the list of categories and we separate them by the passed separator.

So all we have to do now is call that function within or out side the loop, something like this (if within the loop):

<?php echo get_categories_with_images($post->ID,' ,'); ?>

that's it all done, but really you can change this function to return any other field of the extra category fields you want.
Enjoy.

Ohad Raz

WordPress Consultant, a WordPress Developer and a WordPress Freelancer With over 10 years experience in architecting web sites and applications. WordPress Development moderator and somethimes Plugin Developer.