0

I'm building a Solr instance in a server and I'd like to replace the wordpress search with it. I tested some Solr-Wordpress plugins but they don't have the flexibility and simplicity I need.

So what I'd like to do is to take the search query from the user and then making an request to the Solr server which will return a list of wp_posts id's. Then I'll pass this list to wp_query and show the user the items.

The code may look like the following:

        $url = 'http://{SOLR_IP}:{SOLR_PORT}/solr/{CORE_NAME}/select?indent=on&q={ DESIRED_QUERY }&wt=json';
        $result = file_get_contents($url);
        $data = json_decode($result, true);

        $ids = array();
        foreach ($data['response']['docs'] as $item)
            array_push($ids, $item['id']);


        $args = array(
           'post__in'      => $ids
        );
        $the_query = new WP_Query( $args );

The problem is: I don't know where to put this code in order to replace the original search query in a clean way. I've been looking at both search.php and searchform.php but I don't really know what to do.

  • Replace the call to search() in your search.php template to call your solr php instead. Then call your own search field that's linked to your solr logic. – Nathaniel Flick May 12 '17 at 4:07
0

Sorry about my english. I think you must use the build-in query hook to send your posts ids to the main query. It use the pre_get_posts hook. That will allow you to change the query after it's creation, and before it's execution.

add_action('pre_get_posts', 'my_search_query');
function my_search_query($query) {
    if($query->is_search() && $query->is_main_query() && get_query_var('s', false)) {   
        // Get the "s" query arg from the initial search
        $desired_query = get_query_var('s', false);

        // Your code
        $url = 'http://{SOLR_IP}:{SOLR_PORT}/solr/{CORE_NAME}/select?indent=on&q={ DESIRED_QUERY }&wt=json';
        $result = file_get_contents($url);
        $data = json_decode($result, true);

        $ids = array();
        foreach ($data['response']['docs'] as $item)
        {
            array_push($ids, $item['id']);          
        }

        // Update the main query
        $query->set('post__in' => $ids);
    }
    return $query;
}

You will update the main query with your new ids from your Solr system. There is probably better ways to get the search query like using get_search_query but I'm not sure that this function is defined during pre_get_posts hook.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.