Tokyo, Japan |

========================================================================================================================================================================================================================

Display a comma-separated list of categories for a post in WordPress

Often you’ll come across an article that shows the category (or categories) under which the article was filed. How do you achieve this in WordPress?

There are a couple of ways. If you’re inside the loop, it’s simple:

<?php the_category(', '); ?>

This will list all the categories with links, separated by commas and in alphabetical order. It doesn’t necessarily have to be a comma (you could just replace the comma in the above code with some other character).

It gets a bit more complicated if you’re outside the loop. In that case, do this:

<?php
$catList = '';
foreach((get_the_category()) as $cat) {
	$catID = get_cat_ID( $cat->cat_name );
	$catLink = get_category_link( $catID );
	if(!empty($catList)) {
		$catList .= ', ';
	}
	$catList .= '<a href="'.$catLink.'">'.$cat->cat_name.'</a>';
}
echo $catList;
?>

Comments