Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Blogs

  • Print
  • + Share This
From the author of

The Code

Let me start by showing you the code I came up with for my site. You can see the results at the top of each post. Here’s the code:

<?php foreach((get_the_category()) as $cat)
 { echo ’<a href="’ . $cat->cat_ID . ’" title="Subscribe to the ’ . $cat->cat_name . ’ topic feed"><img src="" alt="RSS" border="0" align="top" /></a><a href="’ . $cat->cat_ID . ’" title="Read more articles in ’ . $cat->cat_name . ’">’ . $cat->cat_name . ’</a>   ’; } ?>

Looks scary, huh? It isn’t, really, if you break it down into its components.

According to the Codex, the get_the_category tag does the following:

Returns an array of objects, one object for each category assigned to the post. This tag must be used within The Loop.... This function does not display anything; you should access the objects and then echo or otherwise use the desired member variables.

Keeping in mind that I really don’t know PHP but do have a knack for learning from examples, I zeroed in on the examples on the page. One showed how the tag could be used to display category images. I used that as the basis for my final code snippet.

The code shown above has several parts:

  • The first part opens the code with the get_the_category tag:
    <?php foreach((get_the_category()) as $cat) { echo ’

    This is right out of the example in the Codex.

  • The next part displays a standard 10 ×10 RSS feed icon that links to the RSS feed code:
    <a href="’ . $cat->cat_ID . ’" title="Subscribe to the ’ . $cat->cat_name . ’ topic feed"><img src="" alt="RSS" border="0" align="top" /></a>

    In this example, get_the_category is used to retrieve the category ID number. That’s put into the string to come up with a complete URL for the feed. Pretty slick, no?

  • The third part displays the name of the category as a link to the category archive:
    <a href="’ . $cat->cat_ID . ’" title="Read more articles in ’ . $cat->cat_name . ’">’ . $cat->cat_name . ’</a>

    In this case, get_the_category is using the category ID and the category name in the link itself, and the category name as the text to be linked.

  • Next, the code inserts three non-breaking spaces ( ) to separate the icon/text link combinations from each other when a post has more than one category:
  • Finally, the last part closes the code, with more PHP stuff that I would have gotten wrong if it weren’t for that example:
    ’; } ?>

    The result is shown in Figure 1, which is an example of the beginning of a post on my site with multiple categories assigned to it.

    Figure 1

    Figure 1 The tiny orange RSS icons are actually links to individual RSS feeds for each category assigned to the post.

  • + Share This
  • 🔖 Save To Your Account