On one of my blogs I needed a way to combine both categories and tags into one unordered list<ul>
. Each item would of course be wrapped in its own list item<li>
. The design I came up with made this a necessary requirement. My initial attempts used the canned WordPress function callsget_the_category_list()
and get_the_tag_list()
which ended up outputting two unordered lists. Not what I wanted.
I searched a bit more, and found that I could get both arrays prior to outputting to the screen. I control the markup this way and wrap them in a single unordered list.
The PHP and HTML
function get_cats_and_tags_list() { $html = '<div class="entry-cats-and-tags"><ul>'; foreach((get_the_category()) as $cat) { $html .= '<li class="post-cat-item">' . '<a href="' . get_category_link($cat->term_id) . '">' . $cat->cat_name . '</a>' . '</li>'; } $posttags = get_the_tags(); if ($posttags) { foreach($posttags as $tag) { $html .= '<li class="post-tag-item">' . '<a href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a>' . '</li>'; } } return $html . '</ul></div>'; }
Notice that I added a special class to that of a category list item and that of a tag list item. This allows me to custom style the categories and tags as my design dictates.
Here is the CSS
.entry-actions .entry-cats-and-tags { max-width: 500px; } .entry-cats-and-tags ul { list-style: none; margin:0; float:left; } .entry-cats-and-tags ul li { float:left; margin-right:5px; line-height: 2.1em; } .entry-cats-and-tags a { font-size: .9em; } .entry-cats-and-tags li.post-cat-item a { background:#f5f5f5; color: #999; border:solid 1px #f5f5f5; } .entry-cats-and-tags li.post-tag-item a { background:#fff; color: #999; border:solid 1px #ddd; } .entry-cats-and-tags li.post-cat-item a:hover, .entry-cats-and-tags li.post-tag-item a:hover { color: #666; text-decoration: none; border:solid 1px #999; } .entry-cats-and-tags ul li.post-cat-item a, .entry-cats-and-tags ul li.post-tag-item a { border-radius: 10px; padding:4px 10px 3px 10px; }
This technique allows me to easily float the <li>
‘s so that they wrap nicely from one line to the next. This is the final result:
You can view it in action here: jibbywasmosthappy.com. I particularly like the mouse over treatment.
Update
After completing this task I noticed that on an individual posts’ page there were no categories or tags being output. So I moved the PHP / HTML code into its own function in functions.php. This allows me to easily make a one line call from any page.
<?php echo get_cats_and_tags_list(); ?>
Happy coding.
Leave a Reply