Friday, 8 September 2017

How to Create a jQuery Autocomplete in Wordpress

How to Create a jquery-ui Autocomplete in wordpress.

Autocomplete provides suggestions while you type into the text field. In Wordpress we fetch dynamically matched pattern.

Include javascript and css files in header.

Create action inside functions.php or inside plugin code.

add_action('wp_head', 'custom_register_scripts');

function custom_register_scripts(){
wp_register_style( 'sangi_jquery_ui_css', plugin_dir_url(__FILE__) . 'css/jquery-ui.css', false,'1.0.0' );
wp_enqueue_style( 'sangi_jquery_ui_css' );

wp_register_script('sangi_jquery_ui_js',plugin_dir_url(__FILE__) . 'js/jquery-ui.js',array('jquery'),'1.1', false);
wp_enqueue_script('sangi_jquery_ui_js');

wp_localize_script( 'sangi_autocomplete', 'jqueryAutocomplete', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'sangi_autocomplete' );
}

Now add script for Autocomplete

jQuery("#destination_id").autocomplete({
source: function(req, response){
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: jqueryAutocomplete.ajaxurl,
data: 'action=wpyog_search_program&term='+req.term,
success: function(data) {
response(jQuery.map(data, function (item) {
return {
label: item.name,
value: item.id
};
}));
}
});
},
select: function(event, ui) {
jQuery("#destination_id").val(ui.item.label); 
jQuery("#program_id").val(ui.item.value); 
return false;
// save selected id to hidden input
},
minLength: 3
});

Create action inside functions.php or inside your plugin code.

add_action('wp_ajax_nopriv_wpyog_search_program', 'wpyog_search_program');
add_action('wp_ajax_get_wpyog_search_program', 'wpyog_search_program');
function wpyog_search_program(){
global $wpdb;
$suggestions=array();
$search_key = $_REQUEST['term'];
$table_trips = $wpdb->prefix . "wpyog_trips"; // Use custom table for data fetch
    $tripRows = $wpdb->get_results("SELECT id, title, description from $table_trips where title like '%$search_key%' or description like '%$search_key%'");
foreach($tripRows as $row){
$suggestion = array();
        $suggestion['id'] = $row->id;
        $suggestion['name'] = (!empty($row->title))?$row->title:$row->description;
$suggestions[]= $suggestion;
}  
    echo json_encode($suggestions);
    // Don't forget to exit!
    exit;
}

1 comment: