List of Categories and List of Tags for WordPress website

There is no standard way to list non-empty categories or output the list of all tags in WordPress.

Here are code of two useful “shortcodes”:

/**
 * Generates list of categories. Set $atts('counts' => true) to show number of items in every category 
 */
function html_list_categories( $atts ) { 
	$terms = get_terms( 'category', array('hide_empty' => true) );
	if ( !$terms ) return '';

	if ( isset($atts['counts']) ) $showCounts = $atts['counts']; else $showCounts = false;

	$li_items = '';
	foreach( $terms as $t ) {
		$li_items .= "\t" . '<li class="cat-item"><a href="' . get_term_link($t) . '"'; 		  
			if ( $t->description != '') $li_items .= ' title="' . $t->description  . '"'; // add title if description is set		  
		$li_items .= '>'. $t->name . "</a>";
			if ( $showCounts ) $li_items .= " (" . $t->count . ")</li>"; // add count if required
		$li_items .= "\n";
	};

	return "\n<ul class=\"cat-list\">\r\n{$li_items}</ul>\n";
};
add_shortcode( 'list_categories', 'html_list_categories' ); 

/**
 * Generates list of tags. Set $atts('counts' => true) to show number of items for every tag
 */
function html_list_tags( $atts ) { 
	$terms = get_terms( 'post_tag', array('hide_empty' => false) );
	if ( !$terms ) return '';
  
	if ( isset($atts['counts']) ) $showCounts = $atts['counts']; else $showCounts = false;

	$li_items = '';
	foreach($terms as $t) {
		$li_items .= "\t" . '<li class="tag-item"><a href="' . get_term_link($t) . '"'; 		  
			if ( $t->description != '') $li_items .= ' title="' . $t->description  . '"'; // add title if description is set		  
		$li_items .= '>'. $t->name . "</a>";
			if ( $showCounts ) $li_items .= " (" . $t->count . ")</li>"; // add count if required
		$li_items .= "\n";
	};
	
	return "\n<ul class=\"tag-list\">\n{$li_items}</ul>\n";
}
add_shortcode( 'list_tags', 'html_list_tags' );

You can add this code directly into your WordPress theme (function.php or header.php file). But we strongly advice to use one of “code plugins”: Code Snippets, PHP Snippets, etc.

To output Category or Tag lists use “shortcode” in your post or page:

[list_categories]

[list_tags counts="true"]

You can style lists in your own way using CSS classes:

.cat-list {
...
}
.cat-item {
...
}
.tag-list {
...
}
.tag-item {
...
}

Author: BgRnD Official

Official representative of BgRnd Team on this website

Leave a Reply