Display Current Post/Page Categories – WordPress

14/06/2014

We all love how simple WordPress is to work with. The developers amongst us also love how simple it is to extend, massage and manipulate WordPress to produce exactly what we, and our clients, need. One simple snippet that we like to use in our design studio is one for displaying a list of the categories for the current page or post. The snippet is made into a shortcode so we can then display the list anywhere we like on any page or post.

We start off by declaring the function that will run when we use the shortcode.

function usd_shows_cats(){

Then we need to get the id of the current page (note that this works outside of the loop)

$page_id = get_queried_object_id();

We then display a title before the list

echo '<h3>Categories</h3>';

We next pull the id into the WordPress core function, get_the_category_list

echo get_the_category_list('','',$page_id);
}

The final piece of the jigsaw is to declare the shortcode we will use and the function it will call

add_shortcode('showscats','usd_shows_cats');

You can then use [showcats] on any page or post. Simple. Here’s the complete code, which can be put in your functions.php file.

function usd_shows_cats(){
 $page_id = get_queried_object_id();
 echo '<h3>Services</h3>';
 echo get_the_category_list('','',$page_id);
}
add_shortcode('showscats','usd_shows_cats');

We can now add the shortcode in our content using,

[showscats]