Skip to content

Instantly share code, notes, and snippets.

@vicso-name
Created November 1, 2021 20:21
Show Gist options
  • Save vicso-name/70bf2de7d607a02f14073ba36b22cdbf to your computer and use it in GitHub Desktop.
Save vicso-name/70bf2de7d607a02f14073ba36b22cdbf to your computer and use it in GitHub Desktop.
Create AJAX WordPress Search
<?
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'] ), 'post_type' => array('page','post') ) );
if( $the_query->have_posts() ) :
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;
wp_reset_postdata();
endif;
die();
}
$("input#keyword").keyup(function() {
if ($(this).val().length > 2) {
$("#datafetch").show();
} else {
$("#datafetch").hide();
}
});
$('#search_submit').on('click',function(){
let searcher = $('#searcher_form');
jQuery.ajax({
url: searcher.attr('action'),
type: searcher.attr('method'),
data: {
action: 'data_fetch',
keyword: $('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
});
<form id="searcher_form" action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST">
<div class="form-group">
<input type="text" name="s" id="keyword" class="input_search form-control">
<input type="hidden" name="action" value="data_fetch">
</div>
<button id="search_submit" type="button" class="btn"><?php _e('Submit', 'alegre'); ?></button>
</form>
<ul id="datafetch"></ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment