You see, the_category template tag outputs the name of every category a post belongs to, but the category names are linked to respective category pages that I do not want my visitors accessing. Here on GlassOcean.net I try to obscure the category pages that WordPress generates because they are not as customizable as I would like. Therefore, I needed a way to list the categories that a post belongs to without the links.
A Google search for “wordpress the_category without links” returned an article by Robert Mirabito titled How to remove link from the_category in WordPress, which led me to the understanding that I would need to use the get_the_category template tag instead of the the_category template tag. However, Robert’s example inserts a space character as the delimiter, and changing this delimiter to something else results in the delimiter appearing after the very last category. So if you used a comma character as the delimiter, you would end up with something like “Posted in Blog, Services,” which looks bad. This led to some more searching.
A Google search for “wordpress get_the_category separator” returned a question posted by nipponese to the WordPress.org forum titled Adding $separator to get_the_category. Is it possible?
I wasn’t too sure about the solution greenshady provided, so I finally decided it was time to learn how to create my own template tags. One last Google search helped me locate an article by Chris Pearson titled How You Can Use WordPress Functions To Run a Smarter Blog, which had enough information to get me started.
I ended up creating the user-functions.php file and uploading it to my active template folder as described in the article, where I included a custom PHP function that would do the work of displaying the categories how I wanted them.
Check out the code:
<?php
function user_the_categories() {
// get all categories for this post
global $cat;
$cat = get_the_category();
// echo the first category
echo $cat[0]->cat_name;
// echo the remaining categories, appending separator
for ($i = 1; $i < count($cat); $i++) {echo ', ' . $cat[$i]->cat_name ;}
}
?>
What this little function does is output the first category name, then for every remaining category output a comma and space (‘, ‘), followed by the category name ($cat[$i]->cat_name). We no longer have to worry about that trailing separator character you will most likely have when providing a separator arg with the get_the_categories template tag.
To use this, all I have to do is include this line in my single.php template file:
<?php user_the_categories(); ?>
And what you end up with on the page looks like this:
Posted in Blog, Services

Glass Ocean is Perry Butler's Blog, Music Productions, Services, and Software Development.