wordpress

There are a couple of fully developed plugins that bring the magic of SOLR into WordPress. However, if you want to just get something up and running without having to install a plugin this article may be for you. Here I describe how to bring a better search experience to your users by editing your theme.

First thing to do is to create a function that will make a call to SOLR and parse the results. For example:

    function do_solr_search($query)
    {
      if (is_null($query) || strlen(trim($query)) === 0)
      {
        error_log('query is empty', 4);
        return array();
      }
      $query = urlencode($query);
    
      $url = "http://solr_host:port/solr/my-core/select/?&wt=json&json.nl=map&q={$query}";
      $results = file_get_contents($url);
      $json_data = json_decode($results, 1);
      if (count($json_data) === 0)
      {
        error_log("no results for: $url", 4);
        $json_data = array();
      }
    
      $docs = array();
      if (array_key_exists('response', $json_data))
      {
        $response = $json_data['response'];
        if (array_key_exists('docs', $response))
        {
          $docs = $response['docs'];
        }
      }
    
      return $docs;
    }

Then modify the search.php script to use this new function:

    <ul>
    <?php
      $docs = do_solr_search($query);
      if (count($docs) > 0)
      {
        foreach($docs as $doc)
        {
          // passes the doc along to the template
          set_query_var( 'doc', $doc );
          get_template_part( 'template-parts/content', 'search' );
        }
      }
      else 
      {
        get_template_part( 'template-parts/content', 'none' );
      }
    ?>
    </ul>