AJAX live search in WordPress

AJAX live search in WordPress

Adding AJAX to a search form makes the experience far more dynamic and user-friendly: results appear while the visitor types. This article walks through how to build one from scratch.

Problem: We need to display search results dynamically in WordPress without a full page reload.

Solution: The approach is straightforward: follow the three steps below.

Step 1. Add the search form

Add the form to the desired page:

<form id="search-form" role="search" action="<?php echo esc_url( home_url( '/' ) ); ?>">
    <div class="form-group">
        <input type="search" name="s" id="search-query"
               placeholder="<?php esc_attr_e( 'Search...', 'domain' ); ?>"
               autocomplete="off" maxlength="64">
        <span class="input-btn">
            <button class="btn btn-custom" type="submit"><?php esc_html_e( 'Search', 'domain' ); ?></button>
        </span>
    </div>
</form>
<ul id="data" class="data" aria-live="polite"></ul>

Step 2. Send the request while the user types

Create the front-end handler. For example, create a js folder and add a script.js file:

( function( $ ) {
    $( function() {
        var minLength = 3;
        var timer;

        $( '#search-query' ).on( 'input', function() {
            var value = $( this ).val();

            clearTimeout( timer );

            if ( value.length < minLength ) {
                $( '#data' ).empty();
                return;
            }

            // Wait until the user stops typing for 300 ms.
            timer = setTimeout( function() {
                $.post( ajax.url, {
                    action:  'fetch_data',
                    keyword: value,
                    nonce:   ajax.nonce
                }, function( data ) {
                    $( '#data' ).show().html( data );
                } );
            }, 300 );
        } );
    } );
} )( jQuery );

The input event also fires on paste and on clearing the field, unlike keyup. The timer is a simple debounce: the request is sent only when the user pauses, not on every keystroke, which keeps the load on the server low.

Step 3. Handle the request in PHP

Set up the back-end handler in functions.php:

add_action( 'wp_enqueue_scripts', 'enqueue_live_search_scripts' );
function enqueue_live_search_scripts() {
    wp_enqueue_script(
        'live-search',
        get_template_directory_uri() . '/js/script.js',
        [ 'jquery' ],
        null,
        true
    );
    wp_localize_script( 'live-search', 'ajax', [
        'url'   => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce( 'search-form-nonce' ),
    ] );
}

add_action( 'wp_ajax_fetch_data',        'fetch_search_data' );
add_action( 'wp_ajax_nopriv_fetch_data', 'fetch_search_data' );
function fetch_search_data() {
    check_ajax_referer( 'search-form-nonce', 'nonce' );

    $keyword = sanitize_text_field( wp_unslash( $_POST['keyword'] ?? '' ) );

    if ( mb_strlen( $keyword ) < 3 ) {
        wp_die();
    }

    $query = new WP_Query( [
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'no_found_rows'  => true,
        'posts_per_page' => 10,
        's'              => $keyword,
    ] );

    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            printf(
                '<li class="result"><a href="%s">%s</a></li>',
                esc_url( get_permalink() ),
                esc_html( get_the_title() )
            );
        }
        wp_reset_postdata();
    } else {
        echo '<li class="no-results">' . esc_html__( 'No results found.', 'domain' ) . '</li>';
    }

    wp_die();
}

Notes

  • The same minimum length (3 characters) is checked on both sides: in JavaScript to save requests, and in PHP because a request can be sent without your script.
  • no_found_rows skips counting the total number of results, which we don’t need without pagination.
  • The titles are escaped with esc_html(), because the response is inserted into the page as HTML.
  • The form keeps working without JavaScript: the field is named s and the form submits to the home URL, so pressing Enter opens the regular search results page.

Sources:

  1. https://wordpress.stackexchange.com/questions/240138/ajax-live-search-for-post-title