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 {
...
}

Hack to Extend the Website content

In this article you’ll find some useful web-mastering tips and tricks. You can use this technique to make own web-site template engine or to extend the website functionality without ruining the old code as it was discussed in the previous article.

Define the new content as a variable. The previous and the next decorators could be dynamic arrays:

$sidebar_before[] = '<h2>Sidebar</h2>';
$sidebar_before[] = 'print_adsense';
$sidebar = <<<END
<p>
Some aside content here...
</p>
END;
$sidebar_after[] = 'block-links.inc';
$sidebar_after[] = '<h3>Advertisement<h3>';
$sidebar_after[] = 'print_adsense';

To call custom functions, include files or just print some html code before and after the main content, the PHP code in your website template should be something like this:

if (isset($sidebar_visible) && $sidebar_visible) {

	echo "\t\t\t<!-- Sidebar -->\n";
	echo "\t\t\t<div id=\"sidebar\" class="$css_class">\n\n";
	
	// Print content before the Sidebar
	if (isset($sidebar_before))
		foreach ($sidebar_before as $s) {
			if (function_exists($s)) call_user_func($s); 
			elseif (is_file($s)) include($s);
			else echo $s;
			echo "\n\n";
		}	

	// Print the Sidebar
	if (isset($sidebar)) echo $sidebar."\n\n";
	
	// Print content after the Sidebar
	if (isset($sidebar_after))
		foreach ($sidebar_after as $s) {
			if (function_exists($s)) call_user_func($s); 
			elseif (is_file($s)) include($s);
			else echo $s;
			echo "\n\n";
		}	
	
	echo "\t\t\t</div>\n";
	echo "\t\t\t<!-- /Sidebar -->\n\n";
} 

If you have any questions relative this article or know some other useful web-master hacks write a comment or contact our team directly.

Adding Categories and Tags into WordPress Pages

Wordpress CMS is a very popular one, but some features and settings are strange.

The most common question people creating content for websites based on this CMS ask is the following:

Why WordPress Posts have Category and Tag settings but WordPress Pages have neither Categories nor Tags?

Here is a quick fix:

// Allow Categories and Tags in GUI of Page Editor 
function add_taxonomies_to_pages() {
	register_taxonomy_for_object_type('category', 'page');
	register_taxonomy_for_object_type('post_tag', 'page');
}
add_action('init', 'add_taxonomies_to_pages');

// Add Pages into Categories and Tags Archives 
function category_and_tag_archives($query) {
	// If you have custom post types add them into this array
	$my_post_array = array('post', 'page'); 

	if ($query->get('category_name') || $query->get('cat'))
		$query->set('post_type', $my_post_array);

	if ($query->get('tag'))
		$query->set('post_type', $my_post_array);
}
if (!is_admin()) {
	add_action('pre_get_posts', 'category_and_tag_archives');
}

You can add this code directly into your WordPress theme (function.php or header.php file).

But a safer way is to use one of plugins allowing to execute PHP code (Code Snippets, PHP Snippets, and so on). In this case WordPress Pages will still have Categories and Tags even if somebody changes (or updates) the theme of your site 🙂

Avoid same IDs for HTML elements

Many back-end developers don’t care about clearance of HTML code. They think it is a front-end developers job…

Yes, but no 🙂 Developers should create a bulletproof code on both sides.

Very often, calling the PHP code, that generates some HTML template, for the second time creates two sets of HTML elements with the same IDs. This is wrong!

Here is a workaround to avoid same IDs for HTML elements using a global variable:

<?php
global $some_global_variable;
if (isset($some_global_variable)) $some_global_variable += 1; else $some_global_variable = 0;   

$form_id = '';
if ($some_global_variable > 0) $form_id = $some_global_variable;
?>

This is an example of HTML template for this hack:

<form role="search" method="get" id="searchForm<?php echo $form_id ?>" class="searchForm" action="/search/">
    <input type="text" id="searchText<?php echo $form_id ?>" name="search" value="" />
    <input type="submit" id="searchButton<?php echo $form_id ?>" value="" />
</form>

Try to be a good programmer every-time and everywhere!

Print any PHP variable easily

PHP developers often need to print value of different variables directly to the HTML code. But very often PHP variable is out of the current scope, so the echo(); function doesn’t help. This PHP function prints any global (or external scope) variable by its name:

function print_var($var = 'domain', $url = '')
{
  global $$var, $$$var;
  if ($url != '')
    echo("<a href=\"$url\">${$var}</a>");
  else
    echo(${$var});
}

If you pass some URL as a second parameter you’ll get a clickable link:

<?php print_var('page') ?>
<?php print_var('domain', '/') ?>
<?php print_var('software', '/download/') ?>
<?php print_var('site', 'http://www.site.com') ?>

We hope this PHP hack will be useful for everybody 🙂