<?php /* ================== Ajax Search ====================== */ // add the ajax fetch js add_action( 'wp_footer', 'ajax_fetch' ); function ajax_fetch() { ?> <script type="text/javascript"> function fetch(){ jQuery.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type: 'post', data: { action: 'data_fetch', keyword: jQuery('#keyword').val() }, success: function(data) { jQuery('#datafetch').html( data ); } }); } </script> add_action( 'wp_footer', 'ajax_fetch' ); function ajax_fetch() { ?> <script type="text/javascript"> function khFunction(){ // on focusout rest inpput field value jQuery('#datafetch').html( " " ); } function fetch(){ //test if there is at least to caracters on the input field if(jQuery('#keyword').val().length > 2){ jQuery.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type: 'post', data: { action: 'data_fetch', keyword: jQuery('#keyword').val() }, success: function(data) { jQuery('#datafetch').html( data ); } }); } } </script> <?php } // the ajax function add_action('wp_ajax_data_fetch' , 'data_fetch'); add_action('wp_ajax_nopriv_data_fetch','data_fetch'); function data_fetch(){ $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'category_name' => 'top-apps', 'post_type' => array('post') ) ); if( $the_query->have_posts() ) : echo '<ul>'; while( $the_query->have_posts() ): $the_query->the_post(); ?> <li><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></li> <?php endwhile; echo '</ul>'; wp_reset_postdata(); endif; die(); }