Skip to content

Instantly share code, notes, and snippets.

@alanef
Created August 26, 2022 07:55
Show Gist options
  • Select an option

  • Save alanef/fcc705187748528312554bfa6b4a81f7 to your computer and use it in GitHub Desktop.

Select an option

Save alanef/fcc705187748528312554bfa6b4a81f7 to your computer and use it in GitHub Desktop.
ajax search
/*
==================
Ajax Search
======================
*/
function ajax_fetch() {
/*
* gatekeep only for page 16
*/
if ( ! is_page( 16 ) ) {
return;
}
/*
* past the gate - add code - this should be done using register_script / enqueue_script
* or add_inline_script escpecially as it is dependednt on jquery
*/
?>
<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);
}
});
}
$("input#keyword").keyup(function () {
if ($(this).val().length > 2) {
$("#datafetch").show();
} else {
$("#datafetch").hide();
}
});
</script>
<?php
}
function data_fetch() {
/*
* Do some gate keeping first
*
* add other appropriate checks
*
*/
if ( ! wp_doing_ajax() ) {
return;
}
if ( ! isset( $_POST['keyword'] ) ) {
return;
}
/*
* through the gate continue
*/
$the_query = new WP_Query( array(
'posts_per_page' => - 1,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => array( 'curso' )
) );
if ( $the_query->have_posts() ) :
echo '<ul>';
while ( $the_query->have_posts() ): $the_query->the_post(); ?>
<div class="search_bar">
<form action="/" method="get" autocomplete="off">
<input type="text" name="s" placeholder="Buscar Evento..." id="keyword" class="input_search"
onkeyup="fetch()">
</form>
<div class="search_result" id="datafetch">
<ul>
<li style="float:left;">Aguarde...</li>
</ul>
</div>
</div>
<li style="float:left;"><a>"><?php the_title();
the_post_thumbnail(); ?></a></li>
<?php endwhile;
echo '</ul>';
wp_reset_postdata();
endif;
die();
}
add_action( 'wp_footer', 'ajax_fetch' );
add_action( 'wp_ajax_data_fetch', 'data_fetch' );
add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' );
/*
==================
End Ajax Search
======================
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment