# Highlight Search Terms in Results

> Wraps the searched words in mark tags in result titles and excerpts, so visitors see why each result matched.

- Type: PHP
- Runs: Frontend only
- Category: [Search](https://wpide.com/library/category/search/)
- Tags: search, highlight, ux
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/highlight-search-terms/

## Code

```php
$wpide_highlight_terms = function ( $text ) {
    if ( ! is_search() || ! in_the_loop() || ! is_string( $text ) ) {
        return $text;
    }

    $terms = array_filter( preg_split( '/\s+/', trim( get_search_query( false ) ) ), function ( $term ) {
        return strlen( $term ) > 1;
    } );

    if ( ! $terms ) {
        return $text;
    }

    $quoted  = array_map( function ( $term ) {
        return preg_quote( $term, '/' );
    }, $terms );
    $pattern = '/(' . implode( '|', $quoted ) . ')(?![^<]*>)/iu';
    $result  = preg_replace( $pattern, '<mark class="search-highlight">$1</mark>', $text );

    return null === $result ? $text : $result;
};

add_filter( 'the_title', $wpide_highlight_terms );
add_filter( 'the_excerpt', $wpide_highlight_terms );
```

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Highlight Search Terms in Results" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
