It is a autocomplete textbox using jquery in PHP. I have changed it according to wordpress users as well. Autocomplete textbox are showing the values by themselves after entering any letter in the textbox. Here we are discussing the autocomplete textbox with filter according to the letter pressed in it.

 

auto

 

We are taking an example of auto completion of a textbox in which we are showing titles of a custom post type that is “event”. So, follow the steps to implement it in your wordpress website :

 

1. STEP 1 : Adding jQuery and css to the page :

       <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>

Sometimes it is not required to add the jQueries and css mentioned in Step 1, because when we are working in wordpress we already have js and css. Just try once by using them or remove them if not required.

 

2. STEP 2 : Add this script at the top of the page.

<script type="text/javascript">
                $(document).ready(function(){
                    $("#myevent_name").autocomplete({ // myevent_name is the id of the textbox on which we are applying auto complete process
                        source:'<?php echo get_bloginfo("template_url");?>/sunil_results.php', // sunil_results.php is the file having all the results
                        minLength:1
                    });
                });
        </script>

 

3. STEP 3 : Prepare sunil_results.php file in your theme and paste the below mentioned code :

<?php
include('../../../wp-load.php');

$term=$_GET["term"]; 

$my_args = array(
          		'post_type'  => 'event',  // post type name
          		"s" => $term              //term we are putting in the textbox
		  		);

$json=array();

$custom_query = new WP_Query( $my_args );

if ( $custom_query->have_posts() ) {
    while ( $custom_query->have_posts() ) {
        $custom_query->the_post();

  			$json[]=array( 'value'=> get_the_title() );

          } // while loop ends
}

echo json_encode($json);
 ?>

 

In this way we will get the results showing in the textbox with filter as per our letter we are putting there. Modify the above code as per your requirement.
If anyone will face any difficulty in implementing this, feel free to ask me by your valuable comments 🙂