Search Issue in the theme

If I am not wrong in my understanding then ☻

search.php takes care of the rendering part and the serachform.php takes care of the triggering of the search event, Right?

An example of searchform.php may look like this →

<form role="search" method="get" class="search-form" action="<?php echo home_url( "https://wordpress.stackexchange.com/" ); ?>">
    <label>
        <span class="screen-reader-text"><?php echo _x( '', 'label','simplisto' ) ?></span>
        <input type="search" class="search-field"
            placeholder="<?php echo esc_attr_x( 'Search', 'placeholder','simplisto' ) ?>"
            value="<?php echo get_search_query() ?>" name="s"
            title="<?php echo esc_attr_x( 'Search for:', 'label','simplisto' ) ?>" />
    </label>
    <input type="submit" class="search-submit"
        value="<?php echo esc_attr_x( 'Search', 'submit button','simplisto' ) ?>" />
</form>

Now I have a search setting that opens up in a popup through jQuery that looks like this →

<div class="overlay" id="searchpop">
        <div class="class1">
            <div class="class2">
                <div class="class3">
                    <span class="close closepopup">X</span>
                    <div class="class 4">
                        <div class="class 5">
                            <i class="fa fa-search searchfield_icon" aria-hidden="true"></i>
                            <input type="text" class="searchfieldinput" placeholder="How can we help you ?">
                       </div>
                    </div>
                </div>
            </div>
        </div>
    </div><!--End search popup -->

How do I integrate so that searches should start working? bit puzzled.

1 Answer
1

Every request sent to http://example.com/?s=string will result in a search query, WordPress will use the search.php to render the output. It doesn’t matter where the request is came from.

If you need to do an AJAX search, you have to write your own function to do the search and then return it. I have an answer here, fully explaining how to implement AJAX in your WordPress installation.

Follow the instructions, and write your own query as follows to do the search:

$args =  array(
    's' => $string // This is how a search functions
    'posts_per_page' => 4
);
$query = new WP_Query($args);
// Now save your query in an array using a loop and return it

To do a live search, you have to bind an action to the keyup or keydown using jQuery. You might as well want to check the user’s input value, since searching for strings lower than 3 characters isn’t always a good idea.

So, assuming you are following the linked answer, and your input’s ID is my-ajax-search, this will send an AJAX request each time user enters anything longer than 3 characters, and append the results to an element that has an ID of $ajax-results:

(function($){
    $('#my-ajax-search').on('keyup',function(){
        var searchString = $(this).value();
        // Check the input value's length
        if (searchString .length > 3) {
            $.get( 'http://example.com/wpnovice/ajax_search/', {
                ajaxString: searchString
            }).done( function( response ) {
                if ( response != null) {
                    $.each(response, function(index, el) {
                        $('#ajax-results').append(
                            '<a href="'+el.url+'">'+
                                '<img src="'+el.thumbnail+'" alt="'+el.title+'"/>'+
                                '<span>'+el.title+'</span>'+
                            '</a>'
                        );
                    });
                }
            });
        }
    });
})(jQuery);

Now let’s register a REST route in the back-end and return the search query:

add_action( 'rest_api_init', function () {
    //Path to AJAX endpoint
    register_rest_route( 'wpnovice', '/ajax_search/', array(
            'methods' => 'GET', 
            'callback' => 'wpnovice_ajax_search' 
    ) );
});
function wpnovice_ajax_search() {
    if (isset($_GET['ajaxString'])) {
        $string = $_GET['ajaxString'];
        $ajax_search = new WP_Query(array( 
                        'posts_per_page' => 8,
                        's' => $string,
                    ));
        if ($ajax_search->have_posts()){
            while ($ajax_search->have_posts()){
                $ajax_search->the_post();
                $data_inner['title'] = get_the_title();
                $data_inner['url'] = get_the_permalink();
                if (has_post_thumbnail()) {
                    $data_inner['thumbnail'] = get_the_post_thumbnail_url(get_the_ID(),'thumbnail');
                }
                $search_result[$ajax_search->current_post] = $data_inner;
            }
            return $search_result;
        } else {
            return null;
        }
    } else {
        return __('You must enter a string to search','text-domain');
    }
}

Leave a Comment