Posted on

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;
}

Leave a Reply

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