0

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?

Thanks!

3 Answers 3

1

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

2

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);
1

sanitize_title_with_dashes should do the trick.

Example:

foreach((get_the_category($post->ID)) as $category)
    $classes [] = sanitize_title_with_dashes($category->cat_name);
3
  • 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
    Commented Jan 13, 2013 at 1:24
  • @Mr.Brown: I added an example.
    – akTed
    Commented Jan 13, 2013 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
    Commented Jan 13, 2013 at 3:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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