Skip to content

Instantly share code, notes, and snippets.

@miniMAC
Created September 7, 2017 12:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miniMAC/8c7311f98f87eb47b531b80e80d4c286 to your computer and use it in GitHub Desktop.
Save miniMAC/8c7311f98f87eb47b531b80e80d4c286 to your computer and use it in GitHub Desktop.
<?php
/**
* Live search
*/
function live_search(){
$the_query = new WP_Query( [
'post_type' => ['posts'],
'posts_per_page' => -1,
's' => esc_attr($_POST['keyword'])
]
);
if ( $the_query->have_posts() ) {
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<li class="live-search-result">
<a class="live-search-item" href="<?php echo esc_url( post_permalink() ); ?>" title="<?php echo __('Go to','yourtheme') .' '. get_the_title(); ?>">
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail('thumbnail');
}
the_title('<h6>','</h6>');
?>
</div>
</a>
</li>
<?php
endwhile;
wp_reset_query();
wp_reset_postdata();
} else {
?>
<li class="live-search-result">
<?php _e('Sorry, the search did not return any results. Try to search with different terms.','yourtheme'); ?>
</li>
<?php
}
die();
}
add_action('wp_ajax_live_search', 'live_search');
add_action('wp_ajax_nopriv_live_search','live_search');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment