pantheon-systems / solr-power

A WordPress plugin to connect to Pantheon's Apache Solr search infrastructure, or your own!
https://wordpress.org/plugins/solr-power/
GNU General Public License v2.0
126 stars 61 forks source link

Make it more intuitive to search against title OR post meta #359

Open danielbachhuber opened 6 years ago

danielbachhuber commented 6 years ago

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.

jhned commented 5 years ago

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.

greenSkin commented 3 years ago

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