Posted on

Year filter from the search query

A good question was asked in the post Natural-language date queries:

Is it possible to extend this so that I can simply add a the year in the search and only results from that year would show?

The answer is yes! Add these functions to your site:

add_filter( 'relevanssi_modify_wp_query', function( $query ) {
    $m = preg_match( '/\b\d{4}\b/', $query->query_vars['s'], $matches );
    if ( 1 === $m ) {
        $year = $matches[0];
        if ( $year > 1900 && $year < 2100 ) {
            global $relevanssi_original_query;
            $relevanssi_original_query = $query->query_vars['s'];

            $query->query_vars['year'] = $year;
            $query->query_vars['s']    = str_replace( $year, '', $query->query_vars['s'] );
        }
    }
    return $query;
} );

add_filter( 'posts_pre_query', function( $a, $b ) {
    global $wp_query, $relevanssi_original_query;
    if ( ! empty( $relevanssi_original_query ) ) {
	    $wp_query->query_vars['s'] = $relevanssi_original_query;
    }
    return $a;
}, 100, 2 );

The code consists of two functions. The first one checks the search query. If there’s a single four-digit number between 1900 and 2100 (change those numbers to whatever is reasonable for your site), the number is removed from the search query and converted into a year parameter.

The second function restores the search query to what it was before the number was removed, so the user doesn’t have to wonder why their search query changed.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

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