Everyone loves to use Categories & Taxonomies within WordPress for good reason, it’s gives your users the ability to filter the types of posts & content they want to read with a single click of a button, but what if you want to control the output of this function, why not role your own version? WordPress has some really powerful functions built in one of them being wp_list_categories() this is great and supports loads of arguments similar to a Post Query but you may want to show your Category links in a more customised way, the snippet below will enable you to do just that.
Here’s a really useful snippet for your WordPress Functions file, it will list all the Categories associated with any given post including a link to that particular Category Archive.
function wp_category_links() {
$categories = get_the_category();
$separator = ' ';
$output = '';
if ( ! empty( $categories ) ) {
foreach( $categories as $category ) {
$output .= '<div class="post-categories"><a class="' .$category->slug. '" rel="tag" href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a></div>' . $separator;
}
echo trim( $output, $separator );
}
}
To use the above simply just call the function within your templates:
<?php wp_category_links() ?>
I hope this helps a couple of people, I use this snippet or similar on pretty much every build I do. Outputting it this way give’s you control of the actual markup involved making adding Icon Typefaces or similar a breeze.