Skip to main contentSkip to footer

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.

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

Indexing attachment file names

…( ‘attachment’ === $post->post_type ) { $content .= ‘ ‘ . basename( $post->guid ); } return $content; } Notice that by default Relevanssi replaces periods with spaces, so “sample.pdf” is indexed as “sample pdf”. That should not be a problem, as also in searching “sample.pdf” becomes “sample pdf”. However, if…Relevanssi has been working nicely for the normal usecase. But how does one setup indexing of attachment files. When someone searches by a file name or an extension like pdf, there are no results. I have enabled ‘attachment’ at Relevanssi ‘Indexing options’ and still there are no results. Relevanssi doesn’t…

Keyword-based search blocking
Update: In Premium 2.15.0 and later versions, you can do spam blocking from Relevanssi settings. Just navigate to the Spam…

Related Posts:

Comment Section:

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed