solr-power icon indicating copy to clipboard operation
solr-power copied to clipboard

Make it more intuitive to search against title OR post meta

Open danielbachhuber opened this issue 7 years ago • 2 comments

If you include a custom field value in indexing options, it's easy assume this would cause the document to appear in matching search results:

image

However, getting the document to appear in search results also requires some code monkery:

<?php

/**
 * Tell WordPress to also look in the 'search_keywords' post meta for search results.
 * By default, this will be title AND post meta, which we filter to OR below.
 */
add_action( 'pre_get_posts', function( $query ) {
	if ( $query->is_search() && $query->is_main_query() ) {
		$query->set( 'meta_query', array(
			array(
				'key'     => 'search_keywords',
				'value'   => $query->get( 's' ),
				'compare' => 'LIKE',
			),
		) );
	}
});

/**
 * Filter the title AND post meta query to be title OR post meta
 */
add_filter( 'solr_select_query', function( $query ){
	$query['query'] = str_replace( 'AND((search_keywords_str:', 'OR((search_keywords_str:', $query['query'] );
	return $query;
});

This should be way more intuitive.

danielbachhuber avatar Jan 22 '18 19:01 danielbachhuber

Yeah no kidding, I've been looking for this for a week.

It's also worth noting that if you're using the Query Monitor plugin, it does NOT reflect the filter change in the "Debug Bar: Solr" panel.

I'd recommend adding this to the documentation about using custom fields.

jhned avatar Dec 27 '18 17:12 jhned

The 'pre_get_posts' seems to break search on admin pages. I added !is_admin() && !empty( $query->get( 's' ) ) to the conditional.

greenSkin avatar Feb 04 '21 21:02 greenSkin