Overriding Autosuggests Limits

Autosuggest provides real-time search suggestions to users as they type. One of the benefits of this feature is that it allows the number of displayed suggestions per search query to be controlled. In this article, we will show you how to limit the Autosuggest results and provide a step-by-step walkthrough of a code snippet that accomplishes this.

Here is a code snippet for overriding the Autosuggest limit:

PHP
add_filter(
	'ep_autosuggest_query_args',
	function( $args ) {
		$args['posts_per_page'] = 5;
		return $args;
	}
);

In the above code snippet, the target filter ep_autosuggest_query_args gives developers the ability to adjust the query arguments associated with the Autosuggest feature. The snippet above modifies the ElasticPress plugin’s Autosuggest feature by changing its query arguments, thereby limiting the display to a maximum of 5 search results per page. The value of the ‘posts_per_page’ argument can also be modified to override the number of results shown to the user.

Let’s break down what each line does:

'ep_autosuggest_query_args': This represents the filter hook’s identifier, designated for the purpose of modifying the Autosuggest query arguments in the ElasticPress plugin.

function( $args ) { ... }: This denotes an anonymous function, also referred to as a closure, which accepts a single argument, $args. The WordPress hook mechanism calls this function when the ‘ep_autosuggest_query_args’ filter is executed.

$args['posts_per_page'] = 5;: Within the scope of the anonymous function, this line of code manipulates the $args array by assigning the value 5 to the ‘posts_per_page’ key. Consequently, the Autosuggest feature will display a maximum of 5 search results per page, as opposed to the default value configured by ElasticPress.

return $args;: The modified $args array is subsequently returned by the anonymous function. The WordPress hook system then passes this adjusted array to the ElasticPress plugin, which in turn uses it to construct the Autosuggest query.

IMPORTANT: If you don’t see your changes applied right away, try going to ElasticPress -> Search Fields & Weighting in your WordPress Dashboard and hitting the Save button. That will associate the new values to your ElasticPress.io account.