Steps
-
Add the PHP code to your theme’s
functions.phpfile or a PHP snippets plugin. -
Save and activate the snippet.
-
Search for a keyword on your website.
-
Matching keywords in post titles will appear highlighted.
/**
* Highlight searched keywords in post titles
*/
function custom_highlight_search_keywords( $title ) {
if ( ! is_search() || is_admin() ) {
return $title;
}
$search_query = get_search_query();
if ( empty( $search_query ) ) {
return $title;
}
$pattern = '/' . preg_quote( $search_query, '/' ) . '/iu';
return preg_replace_callback(
$pattern,
function ( $matches ) {
return '<mark class="search-highlight">'
. esc_html( $matches[0] )
. '</mark>';
},
$title
);
}
add_filter( 'the_title', 'custom_highlight_search_keywords' );
Tested on
WordPress 6.8
Reported by the author on November 16, 2026. WPFolks has not verified this.
Not tested against WordPress 7.1.5. It may still work.
