Skip to main contentSkip to footer

Restricting Did you mean suggestions to one post type

Sometimes it may be necessary to restrict the Did you mean suggestions Relevanssi serves to just one post type. There’s no option for that, as by default the Relevanssi database the Did you mean suggestions use as a source (this only applies to Premium, that is) doesn’t have any information about the post types the words are related to.

However, it does have the post ID, which can be linked to a post type, and there’s a filter hook that lets us modify the query that fetches the words from the database. Then it’s just a question of formulating some extra MySQL code to restrict the words fetched to a particular post type.

Add this code to your theme functions.php to restrict the Did you mean searches (in Premium only) to the current post type restriction:

add_filter('relevanssi_get_words_query', 'rlv_dym_post_type');
function rlv_dym_post_type($q) {
	global $wpdb, $wp_query;
	if (isset($wp_query->query_vars['post_type'])) $post_type = $wp_query->query_vars['post_type'];
	if (empty($post_type)) $post_type = "any";
	if ($post_type != "any") {
		$addition = ' AS rr, ' . $wpdb->posts . ' AS pp WHERE rr.doc = pp.ID AND pp.post_type = "' . $post_type . '" GROUP';
		$q = str_replace('GROUP', $addition, $q);
	}
	return $q;
}

Your account

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

Search

Popular Resources

Modernize
Modernize is a neat Premium theme that has a problem with Relevanssi. Relevanssi highlighting can cause problems on Modernize search…
Using Relevanssi without a search term
Deprecated: Relevanssi has long supported searching without a search term. These instructions are not necessary. Version 1.7.3 introduces the possibility…

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