WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Not sure if "sanitizing" is really the correct phrase to use for this but it was the best one I could think of...anyways, here is the problem:

My function works great like so...

// add category id to body & post classes 
function category_id_class($classes) {
    global $post;
    foreach((get_the_category($post->ID)) as $category)
        $classes [] = $category->cat_name;
        return $classes;
add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');

That works great until the user inputs a category such as "Category 1" with a space. Spaces are obviously not desirable as CSS classes so if we could maybe just have a dash added to replace the space that would be perfect - just not sure how to accomplish that?


share|improve this question
up vote 1 down vote accepted

Just use $category->slug instead of $category->cat_name. Slugs are already lowercase and with dashes instead of spaces.

share|improve this answer

sanitize_html_class sanitizes a html classname to ensure it only contains valid characters.

foreach((get_the_category($post->ID)) as $category)
    $classes [] = sanitize_html_class($category->cat_name);
share|improve this answer

sanitize_title_with_dashes should do the trick.


foreach((get_the_category($post->ID)) as $category)
    $classes [] = sanitize_title_with_dashes($category->cat_name);
share|improve this answer
Thanks for the response! All i see for working examples on their reference page however is to use a specific title, mine is dynamic depending on the category so Im not too sure how to add this to my function unfortunately. – Mr.Brown Jan 13 '13 at 1:24
@Mr.Brown: I added an example. – akTed Jan 13 '13 at 1:48
Really appreciate the help AKTed, I +1'd your response since you went out of the way to show me a working example...I decided to go with pogoking answer since though since his answer was a much cleaner solution. Both are viable options though so thank you! – Mr.Brown Jan 13 '13 at 3:37
You're welcome :) – akTed Jan 13 '13 at 7:03

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.