How To: Create a WordPress Autocomplete Search: No Plugin Required

Advertisement

This is just a short post, direct to the point on how we can create a custom Autocomplete Search in WordPress without the use of Plugin.

Sure there are few alternatives out there using a JS library, but I’m not sure we need a whole library for a simple Autocomplete functionality.

Let’s get started!

HTML

This will contain our display or view.


<form ...="">
<input type="text" name="dropdown-selector">

<!--we'll fill this later with our dynamic data-->
<ul id="entry_departments"></ul>
</form>

JavaScript

To set our data dynamically we need to add it to an inline variable, luckily at WordPress, they’re doing everything to make the coding easily and introduced wp_localize_script() function, this function allows us to add key-value pair and a perfect suit to our need. For this example, we’ll use a custom “entry-department” term.


add_action( 'wp_enqueue_scripts', 'ryscript_enqueue_styles_scripts' );
function ryscript_enqueue_styles_scripts() {
    // Generate departments object
    $departments = array();
    
    $terms = get_terms( array(
        'taxonomy'   =&gt; 'entry-department',
        'hide_empty' =&gt; false,
    ) );

    if ( ! empty( $terms ) &amp;&amp; ! is_wp_error( $terms ) ) {
        foreach ( $terms as $term ) {
            $departments[] = array(
                "id" 	=&gt; $term-&gt;term_id,
                "label" =&gt; $term-&gt;name
            );
        }
    }

    wp_enqueue_script( 'ryscript-autofill-js', JS_PATH . '/dfes-database-scripts.js', array('jquery'), '1.0', true );

    // Get lists of departments
    wp_localize_script( 'ryscript-autofill-js', 'departments',
        $departments
    );
}

Now that our data are ready, let’s create the event to fill.


$('input[name="dropdown-selector"]').on("keyup", function(){
    var departmentTerm      = $(this).val(),
        entryDepartments    = $("#entry_departments");
    
    // fill departments items later
    var departmentItems = '';

    $.each( departments, function( i, item ) {
        // To make it works in all type-cases we convert both cases to lowercase and check from there

        if( item.label.substr(0, departmentTerm.length).toLowerCase() ==  departmentTerm.toLowerCase() ) {
            // Create lists of item here
            departmentItems += '<li>'
                + '<label for="id_'+ item.id +'">'
                    + '<input type="checkbox" name="department[]" id="id_'+ item.id +'" value="'+ item.id +'"> <span class="checkmark"></span>'
                    + item.label
                + '</label>'
            + '</li>';
        }
    });
    
    if( null == departmentItems
        || "" == departmentItems ) {
        
        // set empty placeholder if no matching department
        departmentItems = '<li>No matching department.</li>';
    }
    
    entryDepartments.html( departmentItems );
});

That’s it, happy coding!

Advertisement