msaari / relevanssi-light

Relevanssi Light fulltext search
17 stars 1 forks source link

add a filter or option to use boolean mode with default wildcard on? #14

Closed theodejager closed 1 year ago

theodejager commented 1 year ago

Hi, first of all thanks for the plugin, I really like the code and implementation!

I was actually fixing the same problem this plugin sets out to do by squeezing all post meta (mostly ACF flexible content) into an unused post_content or post_excerpt, but this does it faster and in a neater way.

However, what really lacks in comparison to the regular WP search (and my makeshift solution) is the lack of partial matches.

Related to this support point: https://wordpress.org/support/topic/possible-to-use-partial-matches/

Is it possible to add an option or filter to the plugin so that boolean mode can be triggered on/off and have a wildcard asterisk appended to the match query?

Something to this effect?

function relevanssi_light_posts_search( $search, $query ) {
    $mode = '';
    /**
     * Sets the mode for the fulltext search. Defaults to NATURAL LANGUAGE.
     *
     * @param boolean If true, enables BOOLEAN MODE.
     */
    if ( apply_filters( 'relevanssi_light_boolean_mode', false ) ) {
        $mode = 'IN BOOLEAN MODE';
    }
    if ( isset( $query->query['s'] ) && ! empty( $query->query['s'] ) ) {
        $new_search = " AND MATCH(post_title,post_excerpt,post_content,relevanssi_light_data) AGAINST('" . $query->query['s'] . "' $mode)";
        $search = apply_filters( 'relevanssi_light_posts_search_query', $new_search, $query );
    }
    return $search;
}

add_filter( 'relevanssi_light_posts_search_query', 'wildcard_relevanssi_search' );

function wildcard_relevanssi_search( $search, $query ) {
    return " AND MATCH(post_title,post_excerpt,post_content,relevanssi_light_data) AGAINST('" . '*' . $query->query['s'] . '*' . " IN BOOLEAN MODE)";
}

Just as an example, glad to hear of a better way of solving this problem. Thanks!

msaari commented 1 year ago

I suppose it's possible to add a filter hook there. I think this should also work:

add_filter( 'relevanssi_light_boolean_mode', '__return_true' );
add_action( 'pre_get_posts', function( $query ) {
    if ( isset( $query->query_vars['s'] ) ) {
        $query->query_vars['s'] = '*' . $query->query_vars['s'] . '*';
    }
} );
theodejager commented 1 year ago

thanks for the tip, works!