Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress AJAX Live Search of Post Title
<!-- // The HTML (could be part of page content) // -->
<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="datafetch">Search results will appear here</div>
<?php
// 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>
<?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'] ),
'post_type' => 'post'
)
);
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
@val-to

This comment has been minimized.

Copy link

@val-to val-to commented Nov 15, 2019

Hi Alex. Isis that still a secure solution? Can i use this code now?

@alexmustin

This comment has been minimized.

Copy link
Owner Author

@alexmustin alexmustin commented Nov 15, 2019

Hi val-to.

Yes, I am using this code for a WordPress plugin and it still works great!

@val-to

This comment has been minimized.

Copy link

@val-to val-to commented Nov 15, 2019

Hi val-to.

Yes, I am using this code for a WordPress plugin and it still works great!

Thank you! Great job! :-) Greetings from Switzerland.

@val-to

This comment has been minimized.

Copy link

@val-to val-to commented Feb 5, 2020

Hi Alex. How can I include a timeout? I would like the script to be executed after 300 milliseconds.

@val-to

This comment has been minimized.

Copy link

@val-to val-to commented Feb 5, 2020

Is this the right way?

// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>

<script type="text/javascript"> var search_timeout = null function fetch(){ clearTimeout(search_timeout); search_timeout = setTimeout(function(){ $.ajax({ url: '', type: 'post', data: { action: 'data_fetch', keyword: jQuery('#keyword').val() }, success: function(data) { $('#datafetch').html( data ); } }); }, 300); } </script>
@Vicky-Intelligaia

This comment has been minimized.

Copy link

@Vicky-Intelligaia Vicky-Intelligaia commented Oct 6, 2020

HI Alex,
can we have something so that it will only search for the exact keyword. Right now it list many title which are not related to our searched keyword.
Please help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment