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 60 forks source link

Issue making Ajax Requests without breaking Admin Ajax requests #509

Closed ChristopherMWood closed 2 years ago

ChristopherMWood commented 2 years ago

I'm working on a site that uses Solr Power to run many different search components across the site. Each component targets a different set of Content Types and gets called in a combination of Ajax calls for the site header and non ajax calls for the primary site search page. My issue is that to get my custom components to make ajax requests I need to set the solr_allow_ajax field to true. But when I do this, our ajax media search in the admin area breaks at the same time because the plugin overwrites all ajax requests. So how are you able to make custom ajax requests that don't replace all ajax requests?

This is an example of the request we do to WP_Query using a custom WP ajax function. With ajax set to true it returns a score weighted search. With it turned off it returns the Wordpress search.

    $result = new WP_Query(array(
        'solr_integrate' => true,
        'posts_per_page' => -1,
        's' => $searchTerm,
        'post_type' => $contentTypes,
        'post_status' => 'publish',
    ));
danielbachhuber commented 2 years ago

Hey @ChristopherMWood,

Thanks for the question!

So how are you able to make custom ajax requests that don't replace all ajax requests?

What do you think about something like this?

add_filter(
    'solr_allow_ajax',
    function( $retval ) {
        if ( ! empty( $_GET['solr_allow_ajax'] ) ) {
            return true;
        }
        return $retval;
    }
);

With this code snippet applied, you could add an extra solr_allow_ajax=1 in your request to enable Solr.

ChristopherMWood commented 2 years ago

@danielbachhuber You are a life saver, that worked like a charm, such a great idea. The only change I made was move the $_GET to $_REQUEST for my setup. Thank you so much for the quick reply and idea!

add_filter(
    'solr_allow_ajax',
    function( $retval ) {
        if ( ! empty( $_REQUEST['solr_allow_ajax'] ) ) {
            return true;
        }
        return $retval;
    }
);