Last week I was building a theme that incorporated an open-source CSS framework. Adding classes to various front-end elements was straightforward enough. But when it came to post content, things got tricky — the content is output by WordPress itself, so I had no control over the classes being used.
I asked @desin (the author of the “I Love Boiled Fish” blog) if there was a way to add classes without writing JavaScript. He suggested I look into the content filter documentation. After some research, the problem was solved.
Here’s the code — feel free to use it as reference. Copy the following and paste it right below the <?php line in your theme’s functions.php file:
# Automatically add img-res class to img tags in post content
function img_paragraph($content){
return preg_replace('/<img([^>]+)?>/', '<img$1 class="img-res">', $content);
}
add_filter('the_content', 'img_paragraph');
Similarly, if you want to target p tags, the code would be:
# Automatically add mt1em, mb1em, and lh-180 classes to p tags in post content
function p_paragraph($content){
return preg_replace('/<p([^>]+)?>/', '<p$1 class="mt1em mb1em lh-180">', $content);
}
add_filter('the_content', 'p_paragraph');