If you create custom themes in WordPress and have often wished for a simple, uncomplicated way of using post category names as a class or ID name, then this next little tip is for you.
Category Sprites Example
Let’s say you’re building a cool food blog with 3 primary (although slightly unrealistic and entertaining) categories:
- Sushi
- Lobster
- Turkey
You’ve just created a nice sprite which includes individual icons related to each category above. You know, something along the lines of:
Great – good job so far.
Now…onto the really fun stuff. You know you’ll be displaying the latest of these awesome food posts on the home page, and each post needs to display the correct icon for the category it belongs to. In addition, wouldn’t it be nice if you could get to the lobster archive by clicking on the lobster? No problem. To display each sprite, we’ll use some basic css, and we’ll ask WordPress to display the category slug as an ID name for each category so we can style these linked icons with ease. Here we go.
The Code You Seek
<?php foreach((get_the_category()) as $category) { echo '<a href="' . get_category_link( $category->term_id ) . '"id="'. $category->slug .'" class="sprites" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . ' ></a>'; } ?>
In short…get the category link, use the category slug as the ID, add the class “sprite,” and give each link the following title while you’re at it: View all posts in [Category Name], which results in:
<a href="http://www.awesomefoodblog.com/lobster" id="lobster" class="sprite" title="View all posts in Lobster"></a>
To display your icon from your sprite, your css might be something along the lines of:
a#lobster { display:block; width:160px; height:240px; background-position:-293px -46px; } .sprite { background:url(images/sprite.png) no-repeat left top; }
And there you have it.