Category description using get_the category()

I never cease to be amazed by the power of WordPress with its many built-in functions and template tags. Whilst the commonly used functions, such as wp_list_categories(), are often used in themes, there are a number of less well known, but equally useful, functions available which can provide some interesting possibilities for displaying content on your site.

The WordPress get_the_category() function is a perfect example of this, and provides a powerful way to extract data from your database and display it on your site. In this brief tutorial I show you one of the many ways in which this function can be used; in this example, to display a category description in the archive pages.

The scenario

How to display a category description at the top of all category archive pages? That was the question I found myself answering on the popular Studiopress support forum. The forum poster wanted to find a way to display a category-specific description, at the top of all category archive pages, in order to give site visitors more information about the posts filed under each category.

As this is something that many WordPress users might be interested in, I thought it would make an interesting topic for a tutorial.

Thinking through the scenario

Before we get stuck into code let’s take a moment to think through what is required.

Firstly, our code needs to affect only the category archive pages which, depending on your theme, will most likely be named either category.php or archive.php.

Secondly, our code needs to be within the Loop in the category archive page. Why? So that we know which category is being displayed and therefore can display the description appropriate for that category.

Thirdly, we need a category description. WordPress provides an easy way to create this via the Dashboard > Posts > Categories screen where you can create your own decription for each category.

Finally, we need a way to pull all of this together, and the get_the_category() function is exactly what we need.

The get_the_category() function

You can read more details about this function on the WordPress Codex here but here’s a brief description of its main features:

1. Returns an array of objects, one object for each category assigned to the post. Each object (or container, if that makes more sense to the non-programmer) contains the following member variables:

  • cat_ID – the category id (also stored as ‘term_id’)
  • cat_name – the category name (also stored as ‘name’)
  • category_nicename – a slug generated from the category name (also stored as ‘slug’)
  • category_description – the category description (also stored as ‘description’)
  • category_parent – the category id of the current category’s parent. ‘0’ for no parents. (also stored as ‘parent’)
  • category_count – the number of uses of this category (also stored as ‘count’)

2. The function get_the_category() must be used within the Loop.

3. The function doesn’t return anything directly to the browser, so the object member variables generated by the function need to be echoed in order to appear in the browser.

Now we know this, let’s put together the code for displaying the category description.

The code required

In either category.php or archive.php (depending on your theme), find the start of the Loop which should look something like this:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

And replace this line of code with the following:

<?php
if (have_posts()) :
   	if ( is_category() ) {
       	foreach (get_the_category() as $category); ?>
       	<div>
	       	<h2><?php echo $category->cat_name; ?></h2>
    	   	<p><?php echo $category->category_description; ?></p>
       	</div>
	<?php }
    while (have_posts()) : the_post(); ?>

Lines 2 and 10: These are simply the start of the normal Loop code.

Line 3 and 9: This conditional statement checks that we are in a category archive page and not a tags, author, or date archive page. This is more important if your archives are generated by a single archive.php, but is not needed if you use a category.php file. Having said that, I think it is always good practice to test a condition before generating output so as to reduce the possibility of errors or unexpected results in certain situations.

Line 4: This line foreach (get_the_category() as $category) is where our function creates an object named $category which stores the member variables listed previously. The foreach PHP function means that such an object is created for each category assigned to the post. We shall come back to what this means, and its limitations, later on.

Line 5 to 8: This is what will be displayed in the browser. In this example I’m wrapped the output in DIV tags so that I can easily apply specific styles, should I wish, via CSS. The next lines access the member variables, in this case the category name and the category description, and outputs them to the browser in h2 and paragraph tags respectively.

Line 6 and 7: This is where we extract the category name and category description from our $category object. Note that the syntax is simply $object->variable, therefore:

$category->cat_name retrieves the category name;

$category->category_description retrieves the category description.

Also note that we need to preface each of these sections of code with echo in order to see anything in the browser when viewing the page.

That’s it! We now have the category title and description displayed at the top of every category archive page. Don’t forget to add a category description in Dashboard > Posts > Categories!

Taking it further

This code works perfectly when posts are only ever assigned to one category and sub-categories are not being used. However, it is not so useful if posts are assigned to more than one category and/or you are using sub-categories.

In either of these cases it will be necessary to add more code in order to correctly identify which category description should be displayed (a post assigned to two categories will, potentially, have two category descriptions). How we deal with these situations will be the subject of the next article in this series.

Related articles: 

Comments

  1. Thanks Ade – this was very helpful! Now, when will you be doing the next article concerning posts assigned to two categories? 🙂

  2. Ok, ok, ok! 🙂

    Thanks for the reminder – I’ll get on it! 😀

  3. J. Killinger says:

    Thanks for this excellent post. This is a method that I was wondering about for a client requirement on my latest project, it’s a nice a solution. Thanks for sharing.

    JK

  4. Ade – thanks for the info. Jill – thanks for bringing this to my attention.

  5. In the Studio Press Magazine theme, adding text to the Posts>Categories>Description field, populates the title tag on the Category navigation bar. How do I change this?

    • Hi,

      This is a WP issue, not a theme issue. WP automatically adds a title attribute of “View all post filed under…” to category links generated by wp_list_categories(), or uses the category description for this, if it exists.

      If you want to display different title text, you either have to hack a core file (not recommended), or see if there is a filter you can hook into to write your own function. If I get time, I’ll look into this.

      🙂

Leave a Reply to gadget Cancel reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*


four − 4 =