I’d like to replace the existing search function with an external query (from Solr) but I’m having trouble showing the results in the search.php page. This is the code I have in functions.php:

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)) {   

    $desired_query = get_query_var('s', false);

    $url = 'http://{SOLR_SERVER}:8983/solr/{CORE}/select?indent=on&q=' . $desired_query . '~2&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']);
    }

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $query = new WP_Query(array(
        'post__in' => $ids,
        'post_type' => array('last-news','blog'), 
        'paged' => $paged, 
        'posts_per_page' => 5,
    ));

}
return $query;
}

And this is the search.php:

<section class="content">
    <div class="page-title pad group">
        <h1>
        <?php if ( have_posts() ): ?><i class="fa fa-search"></i><?php endif; ?>
        <?php if ( !have_posts() ): ?><i class="fa fa-exclamation-circle"></i><?php endif; ?>
        <?php echo $wp_query->found_posts  ?>
        <?php _e('Search Results','theme'); ?>
        </h1>
    </div>

    <div class="pad group">

        <div class="notebox">
            <?php _e('Found','theme'); ?> "<span><?php echo get_search_query(); ?></span>".
            <?php if ( !have_posts() ): ?>
                <?php _e('Try with another term:','theme'); ?>
            <?php endif; ?>
            <div class="search-again">
                <?php get_search_form(); ?>
            </div>
        </div>

        <?php 
            if ( have_posts() ) : ?>

            <div class="post-list group">
                <?php $i = 1;  while ( have_posts() ): the_post(); 
                echo '<div class="post-row">';
                 get_template_part('content'); echo '</div>'; endwhile;  ?>
            </div><!--/.post-list-->

            <?php get_template_part('inc/pagination'); ?>

        <?php endif; ?>

    </div><!--/.pad-->

</section><!--/.content-->

The echo $wp_query->found_posts returns the number ‘100’ so it seems to be getting something but then the have_posts() functions returns a false value.

What am I doing wrong? I just want to return the posts in the $ids array whenever a search is done, I don’t need no other filter.

Read more here: Replacing search results with custom external query


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: