relevanssi_modify_wp_query

apply_filters( 'relevanssi_modify_wp_query', WP_Query $query );

This filter hook can be used to modify the WP_Query object before Relevanssi sees it.

Parameters

$query
(WP_Query) The query object.

More information

If you want to modify the search parameters somehow, this is the best filter hook to do so. This serves a similar function to the pre_get_posts action hook and you can do most things with either of these hooks. However, when doing modifications that only apply to the search, relevanssi_modify_wp_query is easier to use because it only applies to Relevanssi searches. pre_get_posts is applied everywhere, so if you want to only modify the search, you need to first check that the query is for a search.

(Note that pre_get_posts is an action, not a filter, and does not need to return the modified query. The query is passed as a reference. relevanssi_modify_wp_query is a filter, and needs to return the modified query.)

This is generally the right place to do any modifications to the query variables. Sometimes you see cases where the search query parameters are modified in the search results template and the query is then run again, like this:

<?php
/**
 * The template for displaying search results pages
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
 *
 * @package WordPress
 * @subpackage Twenty_Nineteen
 * @since Twenty Nineteen 1.0
 */

get_header();

$args = array(
  's'           => get_search_query(),
  'numberposts' => 15,
  'post_type'   => 'post,page,custom_post_type',
);

$query = new WP_Query();
$query->parse_query( $args );
relevanssi_do_query( $query );

?>

	<div id="primary" class="content-area">
		<main id="main" class="site-main">

		<?php if ( $query->have_posts() ) : ?>

        <?php // ... and so on.

This is wrong. This causes WordPress to run the default query, then you create a new query and run that, so every search becomes two searches. That causes unnecessary server resource use and slows down searching. Unless you really want to run multiple queries, don’t do this.

Instead, adjust the parameters in a relevanssi_modify_wp_query filter function:

add_filter( 'relevanssi_modify_wp_query', 'rlv_adjust_search' );
function rlv_adjust_search( $query ) {
  $query->set( 'numberposts', 15 );
  $query->set( 'post_type', 'post,page,custom_post_type' );
  return $query;
}

This method is cleaner, doesn’t require modifications to the template, saves server resources and gets you search results faster. It’s also much easier to maintain.

Examples