Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Info about this Paste: https://wordpress.stackexchange.com/a/299154/137402
- * Start copying below this comment, whichever applies.
- */
- HTML form: (Change the value of the parent_page_id field, if you're not targeting
- the current Page.)
- <input type="text" name="keyword" id="keyword" onkeyup="fetch()" />
- <input type="hidden" name="parent_page_id" id="parent_page_id" value="<?php the_ID(); ?>" />
- <div id="datafetch">Search results will appear here</div>
- AJAX call:
- 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(),
- parent_page_id: jQuery( '#parent_page_id' ).val()
- },
- success: function(data) {
- jQuery('#datafetch').html( data );
- }
- });
- }
- </script>
- <?php
- }
- AJAX handler (in functions.php):
- add_action('wp_ajax_data_fetch' , 'data_fetch');
- add_action('wp_ajax_nopriv_data_fetch','data_fetch');
- function data_fetch(){
- $parent_page_id = (int) filter_input( INPUT_POST, 'parent_page_id' );
- $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr(
- $_POST['keyword'] ), 'post_type' => 'page', 'post_parent' => $parent_page_id ) );
- if( $the_query->have_posts() ) :
- while( $the_query->have_posts() ): $the_query->the_post(); ?>
- <h2><a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title();?></a></h2>
- <?php endwhile;
- wp_reset_query();
- endif;
- wp_die();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement