Ajax search functionality in WordPress

Implementing AJAX search functionality in WordPress enhances user experience by enabling live search results without requiring page reloads. Here’s how you can add this functionality step by step:

1. Add JavaScript for AJAX Request
Include custom JavaScript to handle the AJAX request. Add the script file to your theme:

Create a js folder in your theme directory and add a file like ajax-search.js.
Add the following code in functions.php to enqueue the script:

function enqueue_ajax_search_script() {
    wp_enqueue_script('ajax-search', get_template_directory_uri() . '/js/ajax-search.js', ['jquery'], null, true);
    wp_localize_script('ajax-search', 'ajax_object', [
        'ajax_url' => admin_url('admin-ajax.php'),
    ]);
}
add_action('wp_enqueue_scripts', 'enqueue_ajax_search_script');

2. Add AJAX Logic in JavaScript
Edit ajax-search.js:

jQuery(document).ready(function ($) {
    $('#search-input').on('keyup', function () {
        const query = $(this).val();
        $.ajax({
            url: ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'ajax_search',
                query: query,
            },
            success: function (response) {
                $('#search-results').html(response);
            },
        });
    });
});

3. Handle the AJAX Request in PHP
Define the PHP function in functions.php to process the AJAX request and return results:

function handle_ajax_search() {
    $query = sanitize_text_field($_POST['query']);
    $args = [
        'post_type' => 'post',
        's' => $query,
        'posts_per_page' => 5,
    ];
    $search_query = new WP_Query($args);

    if ($search_query->have_posts()) {
        while ($search_query->have_posts()) {
            $search_query->the_post();
            echo '<div><a href="' . get_permalink() . '">' . get_the_title() . '</a></div>';
        }
    } else {
        echo '<div>No results found.</div>';
    }
    wp_die(); // Stops execution.
}
add_action('wp_ajax_ajax_search', 'handle_ajax_search');
add_action('wp_ajax_nopriv_ajax_search', 'handle_ajax_search');

Implementing AJAX search functionality in WordPress enhances user experience by enabling live search results without requiring page reloads. Here’s how you can add this functionality step by step:

1. Add JavaScript for AJAX Request
Include custom JavaScript to handle the AJAX request. Add the script file to your theme:

Create a js folder in your theme directory and add a file like ajax-search.js.
Add the following code in functions.php to enqueue the script:

function enqueue_ajax_search_script() {
    wp_enqueue_script('ajax-search', get_template_directory_uri() . '/js/ajax-search.js', ['jquery'], null, true);
    wp_localize_script('ajax-search', 'ajax_object', [
        'ajax_url' => admin_url('admin-ajax.php'),
    ]);
}
add_action('wp_enqueue_scripts', 'enqueue_ajax_search_script');

2. Add AJAX Logic in JavaScript
Edit ajax-search.js:

jQuery(document).ready(function ($) {
    $('#search-input').on('keyup', function () {
        const query = $(this).val();
        $.ajax({
            url: ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'ajax_search',
                query: query,
            },
            success: function (response) {
                $('#search-results').html(response);
            },
        });
    });
});

3. Handle the AJAX Request in PHP
Define the PHP function in functions.php to process the AJAX request and return results:

function handle_ajax_search() {
    $query = sanitize_text_field($_POST['query']);
    $args = [
        'post_type' => 'post',
        's' => $query,
        'posts_per_page' => 5,
    ];
    $search_query = new WP_Query($args);

    if ($search_query->have_posts()) {
        while ($search_query->have_posts()) {
            $search_query->the_post();
            echo '<div><a href="' . get_permalink() . '">' . get_the_title() . '</a></div>';
        }
    } else {
        echo '<div>No results found.</div>';
    }
    wp_die(); // Stops execution.
}
add_action('wp_ajax_ajax_search', 'handle_ajax_search');
add_action('wp_ajax_nopriv_ajax_search', 'handle_ajax_search');

4. Create a Search Form
Add the following HTML where you want the search functionality:

<div id="search-container">
    <input type="text" id="search-input" placeholder="Search...">
    <div id="search-results"></div>
</div>

5. Styling (Optional)
Style your search box and results with CSS for better UI.

#search-results div {
    padding: 10px;
    border-bottom: 1px solid #ccc;
}
#search-results div a {
    text-decoration: none;
    color: #333;
}
#search-results div:hover {
    background-color: #f0f0f0;
}

For a more robust solution, consider plugins like AJAX Search Lite or SearchWP if coding isn’t your preferred method.
Test in different browsers to ensure compatibility.

Here’s the full HTML structure for implementing AJAX search functionality in WordPress:

HTML Structure for AJAX Search

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;AJAX Search in WordPress&lt;/title&gt;
    &lt;style&gt;
        /* Styling the search bar and results */
        #search-container {
            max-width: 500px;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
        #search-input {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        #search-results {
            margin-top: 10px;
            border-top: 1px solid #ddd;
            padding-top: 10px;
        }
        #search-results div {
            padding: 10px;
            border-bottom: 1px solid #ccc;
        }
        #search-results div a {
            text-decoration: none;
            color: #333;
        }
        #search-results div:hover {
            background-color: #f0f0f0;
        }
    &lt;/style&gt;
    &lt;?php wp_head(); ?&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id=&quot;search-container&quot;&gt;
    &lt;input type=&quot;text&quot; id=&quot;search-input&quot; placeholder=&quot;Search...&quot;&gt;
    &lt;div id=&quot;search-results&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;?php wp_footer(); ?&gt;

&lt;script&gt;
    // <a href="https://easywptutorials.com/javascript-functions/">JavaScript for AJAX search functionality</a>
    document.addEventListener('DOMContentLoaded', function () {
        const searchInput = document.getElementById('search-input');
        const searchResults = document.getElementById('search-results');

        searchInput.addEventListener('keyup', function () {
            const query = searchInput.value;

            if (query.length &lt; 3) {
                searchResults.innerHTML = ''; // Show results only for meaningful input
                return;
            }

            const ajaxUrl = &quot;&lt;?php echo admin_url('admin-ajax.php'); ?&gt;&quot;;
            
            // Create an AJAX request
            const xhr = new XMLHttpRequest();
            xhr.open('POST', ajaxUrl, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function () {
                if (xhr.status === 200) {
                    searchResults.innerHTML = xhr.responseText;
                }
            };
            xhr.send(`action=ajax_search&amp;query=${encodeURIComponent(query)}`);
        });
    });
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;

Instructions:

  • Save this HTML structure in a WordPress theme file like search-ajax.php or include the relevant parts in an existing file like header.php or index.php.
  • Add PHP Functions as described earlier to handle the AJAX logic.
  • Make sure to test this code in your WordPress environment.
  • If you need help integrating this into a specific WordPress theme, let me know!

Related Posts


How to Use a Cron Task to Generate Bookings.ics Automatically?

A common way to achieve this is to trigger the function directly via a cron job, without needing a p...

How to Add a Logout Button Under an ‘Account’ Parent Menu in WordPress

Here’s a complete guide to adding a logout link as a dropdown item under an “AccountR...

How to detect YouTube iframe tag in a specific WordPress post

Detecting YouTube Iframes in WordPress Posts This document outlines two primary methods for detectin...

Unable To Update Order Meta in Woocomerce?

Having trouble updating order meta in WooCommerce?  This is a common issue that can stem from vario...

Recent Posts