-
-
Save EricDu/ca401991fe648064e10797a6091b0306 to your computer and use it in GitHub Desktop.
WordPress AJAX Live Search of Post Title
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- // The HTML (could be part of page content) // --> | |
<input type="text" name="keyword" id="keyword" placeholder="Search" onkeyup="fetch()"> | |
<div id="datafetch">Search results will appear here</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
Modified to: | |
1. Add delay before starting the search. | |
2. Search PDFs in the media library only. | |
3. Display results as a list. | |
*/ | |
// add the ajax fetch js | |
add_action( 'wp_footer', 'ajax_fetch' ); | |
function ajax_fetch() { | |
wp_enqueue_script("jquery"); | |
?> | |
<script type="text/javascript"> | |
var search_timeout = null; | |
function fetch(){ | |
clearTimeout(search_timeout); | |
search_timeout = setTimeout(function(){ | |
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 ); | |
} | |
}); | |
}, 300); | |
} | |
</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' => 'attachment', | |
'post_mime_type' =>'application/pdf', | |
'post_status' => 'inherit', | |
) | |
); | |
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment