GET FREE VERSION GET THE PRO VERSION

How To Separate Words And Digits For Search Query

Examples of code snippets to separate words and digits inside one search query and get relevant search results.

In this article

Overview

In this article we will look at a fairly common case where we have both numbers and letters inside a single search word and we want to find results even if the whole word is not represented inside a particular product, but only its numeric or alphabetic part.

Example: we have a product with the title Download ACF 1449.

If a user searches from ACF 1449 or ACF or 1449 he will find that product.

Search results for 'ACF 1449' query

Search results for 'ACF 1449' query

But if he tries to search with a search query ACF1449 - no search results will appear.

Search results for 'ACF1449' query

Search results for 'ACF1449' query

So our goal here is to display the same search results with such search queries like ACF1449 that contain both words and digits together.

Code snippets

Code snippets itself are very simple and do just one thing - separate words and digits that it finds inside one word.

For example, if user types - ACF1449 - with code snippets it will be the same as user type three search queries at the same time: ACF1449, ACF and 1449.

To get such behaviour please use the following code snippet:

add_filter( 'aws_search_terms', 'my_aws_search_terms' );
function my_aws_search_terms( $terms ) {
    if ( $terms ) {
        foreach ($terms as $term) {
            preg_match_all('/([0-9]+|[a-zA-Z]+)/',$term,$matches);
            if ( ! empty( $matches ) ) {
                $terms = array_merge( $terms, $matches[0] );
            }
        }
    }
    return $terms;
}

You need to add it somewhere outside the plugins folder. For example, inside functions.php file of your theme or use some plugin for adding code snippets.

Also, after adding this code you will need to go to the plugin settings page and click the Clear cache button.

After implementing this code example product that we mentioned previously will be visible even with ACF1449 user search query. Just like we wanted.

Search results for 'ACF1449' query after using code snippet

Search results for 'ACF1449' query after using code snippet