WordPress: Remove links from the_category()

The standard way to display the categories a post belongs to is to use the function the_category, e.g, the call the_category(', '); will output:

link, photo, regular, video

As you see the categories are automatically linked to their respective category pages which in most cases is the style needed. Nevertheless there may be situations where you (or your customer) does not want the categories to link anywhere. Unfortunately WordPress does not provide any straightforward method to accomplish this so we have to make a small detour.

There are two ways we can take: rebuild the output or filter the output.

Rebuilding the output

$i = 0;
$sep = ', ';
$cats = '';
foreach ( ( get_the_category() ) as $category ) {
if (0 < $i)
$cats .= $sep;
$cats .= $category->cat_name;
$i++;
}
echo $cats;

(I found the basics for this solution at SydneyFX.)
The code does what we want but it has the disadvantage that it leaves out all the candy provided by the original function. So there has to be a better solution.

Filter the standard output

WordPress is full of filters and as expected there is also a filter for the output of the_category(). So let’s us it:

function no_links($thelist) {
return preg_replace('#([^<]*)#i', '$1', $thelist);
}

add_filter( 'the_category', 'no_links' );

[...] The Loop [..]

remove_filter( 'the_category', 'no_links' );

The function no_links() contains a regular expression which removes all anchors from the string. That’s the whole trick. At the end of your code you should remove the filter again, just in case the categories are displayed on the same page with the standard style.