Posted on

Using AND and NOT for Boolean operators

Relevanssi Premium has support for in-query Boolean operators. Relevanssi uses + and – for the operators: cats -dogs and cats +kittens.

If you prefer instead to use the verbal AND and NOT operators, it only takes one small function in your theme functions.php:

add_filter( 'relevanssi_search_filters', 'rlv_boolean_operators' );
function rlv_boolean_operators( $args ) {
	$args['q'] = str_replace( ' and ', ' +', $args['q'] );
	$args['q'] = str_replace( ' not ', ' -', $args['q'] );
	return $args;

This function looks at the search query and replaces the word AND with a + sign and word NOT with a – sign. A search query can now say cats NOT dogs, and that gets interpreted as cats -dogs, which Relevanssi understands.

6 comments Using AND and NOT for Boolean operators

  1. Hi Mikko, I tested using the AND operator and using 2 terms, like: ‘ cars and bikes’ is throwing results with one of each words. Maybe it is because Im using the free version?
    Is this working fine on the Premium?

    1. Gus, there’s no AND operator like that in Relevanssi. You choose the operator from the searching settings. If you set the operator to “AND” from the searching settings and search for “cars bikes”, you will get results that have both words.

      In Premium, you can set the operator to OR from settings and then do a search for “cars +bikes” or “bikes +cars” to get results with both words.

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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.