How to display the category dropdown auto search list when key press?
I have a search field. There is no issue with the search if I enter anything on this and click on button then it’s redirecting on the page where I can get my search result.
What I am doing is, I have to display the category dropdown auto search list when the user enters any text in the search field. I found one plugin (https://wordpress.org/plugins/ajax-search-lite/) also demo here (https://lite.ajaxsearchpro.com/). I am trying to do the same but I can’t use the plugin.
I need to know what query I have to use on the ajax to get the output?
Form code
function search_form($atts) {
$form = '<section class="universalSearch"><div class="search search-form"><form role="search" method="get" action="' . home_url( '/' ) . '" >
<label class="screen-reader-text" for="s">SEARCH</label>
<input type="search" class="search-field universalSearchField" value="' . get_search_query() . '" name="s" placeholder="Search" />
<input type="submit" id="searchsubmit" class="search-submit" value="'. esc_attr__('Go', 'domain') .'" />
</form></div></section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
(function($) { // ready handler
$(".universalSearchField").keypress(function() {
$.post("/wp-admin/admin-ajax.php", {"action":"universalSearchlist"}, function(response) {
$(".universalSearch").append(response);
console.log( response );
});
});
})(jQuery);
</script>';
return $form;
}
add_shortcode( 'get_search_form', 'search_form');
AjAX code
add_action('wp_ajax_universalSearchlist','universalSearch');
add_action('wp_ajax_nopriv_universalSearchlist','universalSearch');
function universalSearch(){
$data='';
$args = array(
's' => $_REQUEST[ 'universalSearchlist' ],
'cat' => 'category'
);
$the_query = new WP_Query( $args );
foreach ($the_query->posts as $post) {
var_dump($post);
}
//endif;
//die();
return $data;
}
Leave an answer