How to automatically apply CSS to specific words in WordPress posts

To automatically apply CSS to specific words in WordPress posts, you can create a custom function to search for those words and wrap them with a element containing a CSS class. Then, add this function to your theme’s functions.php file.

Follow these steps:

  1. In your WordPress admin dashboard, go to “Appearance” > “Theme Editor.”
  2. In the right sidebar, locate and click on the “functions.php” file.
  3. Add the following code snippet at the end of the file:
function highlight_specific_words($content) {
    $words_to_highlight = array('word1', 'word2', 'word3'); // Replace with your specific words
    $css_class = 'highlighted-word'; // Replace with your desired CSS class

    foreach ($words_to_highlight as $word) {
        $content = preg_replace('/\b(' . preg_quote($word, '/') . ')\b/i', '$1', $content);

    return $content;
add_filter('the_content', 'highlight_specific_words');

Replace ‘word1’, ‘word2’, ‘word3’ with the specific words you want to target, and replace ‘highlighted-word’ with your desired CSS class name.

  1. Click “Update File” to save the changes.
  2. Next, you’ll need to add the CSS styles for the specified class. Go to “Appearance” > “Customize” > “Additional CSS” in your WordPress dashboard.
  3. Add your custom CSS for the desired class:
.highlighted-word {
    /* Add your custom styles here */
    background-color: yellow;
    font-weight: bold;
  1. Click “Publish” to save the changes.

Now, the specified CSS class will be automatically applied to the specific words you’ve defined in your WordPress posts.

Please note that this solution may not work with certain page builders or content generated by plugins. It’s designed to work with the default WordPress post content.

Leave a Reply

Your email address will not be published. Required fields are marked *