Hack: Listing a Post’s Categories

I saw a question in a forum the other day where a site owner wanted to list the categories for a post on the page. Seems like it should be simple, and it is if there is just one category. But if there are multiple categories, it gets tricky.

First, you need to use wp_get_post_categories which takes a post ID, it doesn’t just assume the current post like get_the_category does. Then you get back an array and need to loop through it. You then need to use
get_category_link to get the link to the category page and get_cat_name to get the name of the category from the category ID. Those function names aren’t exact intuitive. Here is a shortcode function you can add to your functions.php or custom plugin.

add_shortcode('showcats','wpshortcode_show_category_links');
function wpshortcode_show_category_links() {
	$categories = wp_get_post_categories(get_the_ID());
	if (!empty($categories)) {
		$list = [];
		foreach($categories as $category) {
			$list[] ='<a href="' . esc_url(get_category_link($category)) . '">' . esc_html(get_cat_name($category)) . '</a>';
		}
		return implode($list,', ');
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *