I have an input text and want it to suggest custom taxonomy terms as soon as i type on it.
These codes below i found after some googling, gives the idea about how to use autocomplete method in WP but i can't figure out how to achieve custom taxonomy terms suggestion in the input box.
suggest.js:
$( '#tags' ).autocomplete(
{
minLength: 2,
source: function( request, response ) {
jQuery.getJSON( MyAjax_object.ajaxurl + "?submittags=?&action=myajax-submit", request, function( data ) {
response( jQuery.map( data, function( item ) {
jQuery.each( item, function( i, val ) {
val.label = val.whatever; // build result for autocomplete from suggestion array data
} );
return item;
} ) );
} );
},
});
functions.php:
function enque_template_scripts() {
wp_enqueue_script( 'myajax_jsfile_handle', get_bloginfo('template_directory')."/suggest.js", array( 'jquery', 'jquery-form', 'json2' ), false, true ); );
wp_localize_script(
'myajax_jsfile_handle',
'MyAjax_object',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'myajax_nonce' => wp_create_nonce( 'myajax_nonce_val' ),
'action' => 'myajax-submit'
)
);
add_action('get_header', 'enque_template_scripts');
function get_my_suggestions() {
// This function should query the database and get results as an array of rows:
// GET the recieved data: 'term' (what has been typed by the user)
$term = $_GET['term']
$suggestions_array = array();
// echo JSON to page and exit.
$response = $_GET["submittags"]."(". json_encode($suggestions_array) .")";
echo $response;
exit;
}
add_action( 'wp_ajax_myajax-submit', 'get_my_suggestions' );
input text:
<input type="text" id="tags" name="submittags" value="" autocomplete="false" />
I guess the trick would be in:
val.label = val.whatever;
and in
get_my_suggestions
function. But how?
Any idea?
Many thanks in advance.