is it possible to use add_filter
or something similar to add the slug
of the category as classname to the the_category()
function?
Right now when using the_category()
the output looks like this â¦
<ul class="post-categories">
<li>
<a href="http://mysite.com/something" title="" rel="category tag">News</a>
</li>
</ul>
Is it possible to somehow get this â¦
<ul class="post-categories">
<li class="category-news">
<a href="http://mysite.com/something" title="" rel="category tag">News</a>
</li>
</ul>
Or something similar, at least some classname with the slug
of the category so I can select it via CSS?
Thank you in advance, matt.
First locate
the_category()
in the Codex. Scroll down to the bottom of the page to “Source Code”. There is a link “the_categfory()
is located in …”. Click the link, you will be redirected to the source code. Alternativly open the filewp-includes/category-template.php
in your IDE or editor.Now search for
function the_category()
. You will see that the function calls another functionget_the_category_list()
. Search for this function too. And now read the code and search forapply_filters()
oradd_action()
As you can see, there is only one
apply_filters()
call at the end of the function. If you read the code carefully, you know now that you can only filter the complete html created bythe_category()
.There are several ways to modifiy the html. DOMDocument is one of them, a good old
preg_replace_callback()
another one.Thats easy, isn’t it? Apply a filter on
the_category
hook. Search for<a followed by some chars but not >[group the chars until <]</a>
, pass the result to the callback function. The callback function retrieve an array with all search results, we pick the last one, this is the text of the link. Then create a class from the text, please sanitize this very well (by your own). Last but not least, insert the class attribute and return the generated result back topreg_replace_callback()
weher it is replaced with the search result.Yes, I like DOM manipulation very much… not 😉
Oh, I forgot. You can do this also with jQuery. Search for the class ‘.post-categories’, grep all link tags inside a list tag, walk over the result and get the href attributes, convert it to a propper classname, add the class with
.addClass(class)
to the link tag.While sanitizing for classNames can be very hard in some languages i prefere @powerbuoy’s comment and figured that out:
i hope that may help, cheers