SHARE
TWEET

wp-stack-exchange-299088

5ally Mar 28th, 2018 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Info about this Paste: https://wordpress.stackexchange.com/a/299154/137402
  3.  * Start copying below this comment, whichever applies.
  4.  */
  5.  
  6. HTML form: (Change the value of the parent_page_id field, if you're not targeting
  7. the current Page.)
  8.  
  9. <input type="text" name="keyword" id="keyword" onkeyup="fetch()" />
  10. <input type="hidden" name="parent_page_id" id="parent_page_id" value="<?php the_ID(); ?>" />
  11. <div id="datafetch">Search results will appear here</div>
  12.  
  13. AJAX call:
  14.  
  15. add_action( 'wp_footer', 'ajax_fetch' );
  16. function ajax_fetch() {
  17. ?>
  18.  
  19. <script type="text/javascript">
  20.  
  21. function fetch(){
  22. jQuery.ajax({
  23.     url: '<?php echo admin_url('admin-ajax.php'); ?>',
  24.     type: 'POST',
  25.     data: {
  26.       action: 'data_fetch',
  27.       keyword: jQuery('#keyword').val(),
  28.       parent_page_id: jQuery( '#parent_page_id' ).val()
  29.     },
  30.     success: function(data) {
  31.         jQuery('#datafetch').html( data );
  32.     }
  33. });
  34. }
  35. </script>
  36. <?php
  37. }
  38.  
  39. AJAX handler (in functions.php):
  40.  
  41. add_action('wp_ajax_data_fetch' , 'data_fetch');
  42. add_action('wp_ajax_nopriv_data_fetch','data_fetch');
  43. function data_fetch(){
  44.  
  45. $parent_page_id = (int) filter_input( INPUT_POST, 'parent_page_id' );
  46. $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr(
  47. $_POST['keyword'] ), 'post_type' => 'page', 'post_parent' => $parent_page_id ) );
  48. if( $the_query->have_posts() ) :
  49.     while( $the_query->have_posts() ): $the_query->the_post(); ?>
  50.  
  51.         <h2><a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title();?></a></h2>
  52.  
  53.     <?php endwhile;
  54.     wp_reset_query();  
  55. endif;
  56.  
  57. wp_die();
  58. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top