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="http://www.marialanger.com/?feed=rss2&cat=’ . $cat->cat_ID . ’" title="Subscribe to the ’ . $cat->cat_name . ’ topic feed"><img src="http://www.marialanger.com/wp-content/images/feedicon.jpg" alt="RSS" border="0" align="top" /></a><a href="http://www.marialanger.com/?cat=’ . $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="http://www.marialanger.com/?feed=rss2&cat=’ . $cat->cat_ID . ’" title="Subscribe to the ’ . $cat->cat_name . ’ topic feed"><img src="http://www.marialanger.com/wp-content/images/feedicon.jpg" 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="http://www.marialanger.com/?cat=’ . $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 The tiny orange RSS icons are actually links to individual RSS feeds for each category assigned to the post.