Bolding specific word(s)/parts of widget title

This bolds the first words (or entire word, if only one) of my widget titles:

add_filter( 'widget_title', function ( $title ) {
    return preg_replace("/^(.+?)( |$)/", "<strong>$0</strong>", $title, 1);
}, 10, 1);

Breaking down the regex pattern, we have:

  • ^ is the start of the line
  • (.+?) is anything between our next group (in this context, a word)
  • ( |$) means either the first space, or the end of the line
    • the first space would be a normal title with multiple words
    • the end of line would mean a space wasn’t found, so the title is just one word

In preg_replace(), we have a fourth attribute set to 1, it’s the limit. This means the replace will only work on the first instance (which doesn’t matter much in this context, as we know $title is always a single line so because of our start of line anchor ^ we know it can only work once always – but hey, why not).

Please keep in mind I put the code in an anonymous function for minimal code (showing off). If this is for a plugin or a public theme, best to stick to doing the function call as you originally did.