How to Add Autocomplete Search to WordPress?

Adding an autocomplete search feature to your WordPress website can significantly enhance user experience by providing instant search suggestions as users type. This functionality is particularly useful for websites with a large amount of content, helping users find what they’re looking for more efficiently. In this article, we will explore various approaches to implementing autocomplete search in WordPress, detailing each method step-by-step.

These are the following approaches:

Table of Content

  • Using a WordPress Plugin
  • Implementing Custom Code with jQuery UI
  • Using an External Service (e.g. Algolia)
  • Implementing Custom Code with JavaScript and AJAX

Using a WordPress Plugin

Utilizing a plugin is the easiest and most straightforward method to add autocomplete search functionality to your WordPress site. Plugins come with pre-built features and settings, allowing you to implement autocomplete without any coding knowledge.

Step 1: Install and Activate the Plugin

  • Go to your WordPress dashboard.
  • Navigate to Plugins > Add New.
  • Search for “autocomplete search” or a specific plugin like “Ajax Search Lite”.
  • Install and activate the plugin.

Autocomplete Plugin

Step 2: Configure the Plugin Settings

  • Once activated, go to the plugin settings.
  • Customize the search settings as per your requirements.
  • Adjust the appearance, data sources, and other options.

Step 3: Embed the Search Form

  • Use the provided short code or widget to place the search form on your desired location, such as the sidebar or header.
// In a widget area
echo do_shortcode('[wpdreams_asp_search]');

Autocomplete Plugin Active

Example: Using the “Ajax Search Lite” plugin:

  • Install and Activate:
  • Configure Settings:
  • Embed Search Form

Output: When users start typing in the search box, they’ll see suggestions based on their input, providing an intuitive and fast search experience.

Ajax Search Lite Plugin

Implementing Custom Code with jQuery UI

For those comfortable with coding, using jQuery UI to implement an autocomplete search provides a highly customizable solution. This method involves integrating jQuery UI’s Autocomplete widget with your WordPress site.

Step 1: Enqueue jQuery UI in WordPress

  • Add the necessary scripts and styles in your functions.php file.

functions.php file

PHP
function enqueue_jquery_ui() {
    wp_enqueue_script('jquery-ui-autocomplete');
    wp_enqueue_style('jquery-ui-css', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css');
}
add_action('wp_enqueue_scripts', 'enqueue_jquery_ui');

Step 2: Create the Search Form

  • Add a search form to your theme (e.g., in header.php).

header.php file

PHP
<form id="searchform" action="<?php echo home_url('/'); ?>" method="get">
    <input type="text" id="autocomplete" name="s" placeholder="Search...">
    <input type="submit" value="Search">
</form>

Step 3: Add jQuery Autocomplete Functionality

  • Implement the jQuery script to handle the autocomplete logic.
JavaScript
jQuery(document).ready(function($) {
    $("#autocomplete").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: ajaxurl,
                dataType: "json",
                data: {
                    term: request.term,
                    action: "autocomplete_search"
                },
                success: function(data) {
                    response(data);
                }
            });
        },
        minLength: 2,
    });
});

Step 4: Handle AJAX Request in WordPress

  • Add the AJAX handler in your functions.php.
PHP
function autocomplete_search() {
    global $wpdb;
    $term = sanitize_text_field($_GET['term']);
    $results = $wpdb->get_results($wpdb->prepare("SELECT post_title FROM $wpdb->posts WHERE post_title LIKE %s AND post_status = 'publish'", '%' . $wpdb->esc_like($term) . '%'), ARRAY_A);
    $suggestions = [];
    foreach ($results as $result) {
        $suggestions[] = $result['post_title'];
    }
    wp_send_json($suggestions);
}
add_action('wp_ajax_autocomplete_search', 'autocomplete_search');
add_action('wp_ajax_nopriv_autocomplete_search', 'autocomplete_search');

Output: Users will see dynamic suggestions from your WordPress posts as they type in the search box.

AutoComplete form

Using an External Service (e.g. Algolia)

Algolia is a powerful search-as-a-service solution that offers fast and customizable autocomplete search features. Integrating Algolia with WordPress involves using their API and the Algolia Search plugin for WordPress.

Step 1: Sign Up for Algolia

  • Create an account on the Algolia website and set up your application.

Step 2: Install the Algolia Plugin

  • In your WordPress dashboard, go to Plugins > Add New.
  • Search for “Algolia Search”.
  • Install and activate the plugin.

Algolia Plugin

Step 3: Configure the Plugin

  • Go to Settings > Algolia Search.
  • Enter your Algolia application ID, search-only API key, and admin API key.
  • Configure indices and search settings.

Step 4: Customize the Search Interface

  • Use the provided templates and widgets to customize the search experience.

Example:

  • Sign Up and Configure Algolia
  • Install Algolia Plugin
  • Configure Plugin Settings

Algolia Customise

Create account and enter those API keys in WordPress dashboard

Algolia Dashboard

Output: Your WordPress site will have a powerful and fast autocomplete search powered by Algolia, providing a seamless search experience.

Algolia Plugin

Implementing Custom Code with JavaScript and AJAX

For a fully custom solution, you can use plain JavaScript and WordPress’s built-in AJAX functionality to create an autocomplete search. This method offers the most flexibility and control over the search feature.

Step 1: Create the Search Form

  • Add a search form to your theme (e.g., in header.php).
PHP
<form id="searchform" action="<?php echo home_url('/'); ?>" method="get">
    <input type="text" id="search-input" name="s" placeholder="Search...">
    <input type="submit" value="Search">
</form>

Step 2: Add JavaScript for Autocomplete:

  • Implement JavaScript to handle input events and make AJAX requests.
JavaScript
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('search-input');
    searchInput.addEventListener('keyup', function() {
        const query = this.value;
        if (query.length > 2) {
            fetch(`${ajaxurl}?action=search_suggestions&term=${query}`)
                .then(response => response.json())
                .then(data => {
                    // Render suggestions
                });
        }
    });
});

Step 3: Handle AJAX Request in WordPress:

  • Add the AJAX handler in your functions.php.
PHP
function search_suggestions() {
    global $wpdb;
    $term = sanitize_text_field($_GET['term']);
    $results = $wpdb->get_results($wpdb->prepare("SELECT post_title FROM $wpdb->posts WHERE post_title LIKE %s AND post_status = 'publish'", '%' . $wpdb->esc_like($term) . '%'), ARRAY_A);
    $suggestions = [];
    foreach ($results as $result) {
        $suggestions[] = $result['post_title'];
    }
    wp_send_json($suggestions);
}
add_action('wp_ajax_search_suggestions', 'search_suggestions');
add_action('wp_ajax_nopriv_search_suggestions', 'search_suggestions');

Output: Users will receive search suggestions in real-time as they type in the search box, providing a custom autocomplete experience.

Conclusion

Implementing an autocomplete search feature in WordPress can greatly enhance user experience by offering real-time search suggestions. Whether you prefer using a plugin for simplicity, leveraging jQuery UI for customization, integrating with an external service like Algolia for performance, or coding a custom solution with JavaScript and AJAX, each method has its advantages. Choose the approach that best fits your needs and technical expertise to improve your WordPress site’s search functionality.