Advertisement
Guest User

Untitled

a guest
Aug 19th, 2015
422
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. //FUNCTIONS PHP
  2.  
  3. // Enqueue script
  4. function ajax_filter_posts_scripts() {
  5. // Enqueue script
  6. wp_register_script('afp_script', get_template_directory_uri() . '/js/ajax-filter-posts.js', false, null, false);
  7. wp_enqueue_script('afp_script');
  8.  
  9. wp_localize_script( 'afp_script', 'afp_vars', array(
  10. 'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
  11. 'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
  12. )
  13. );
  14. }
  15. add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
  16.  
  17. $result = array();
  18.  
  19. // Script for getting posts
  20. function ajax_filter_get_posts( $taxonomy ) {
  21.  
  22. // Verify nonce
  23. if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
  24. die('Permission denied');
  25.  
  26. $taxonomy = $_POST['taxonomy'];
  27.  
  28. // WP Query
  29. $args = array(
  30. 'tag' => $taxonomy,
  31. 'post_type' => 'post',
  32. 'posts_per_page' => -1,
  33. );
  34.  
  35. // If taxonomy is not set, remove key from array and get all posts
  36. if( !$taxonomy ) {
  37. unset( $args['tag'] );
  38. }
  39.  
  40. $query = new WP_Query( $args );
  41.  
  42. if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
  43.  
  44. $result['response'][] = '<h2><a href="'.get_permalink().'">'. get_the_title().'</a></h2>' . get_the_excerpt();
  45. $result['status'] = 'success';
  46.  
  47. endwhile; else:
  48. $result['response'] = '<h2>No posts found</h2>';
  49. $result['status'] = '404';
  50. endif;
  51.  
  52. $result = json_encode($result);
  53. echo $result;
  54.  
  55. die();
  56. }
  57.  
  58. add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
  59. add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
  60.  
  61.  
  62. //TAG.PHP
  63.  
  64. <?php get_header(); ?>
  65.  
  66. <div class="row">
  67.  
  68. <div class="col-md-16">
  69.  
  70. <div class="col-md-4 col-md-offset-1">
  71.  
  72. <h1 class="entry-title"><?php _e( 'Tag Archives: ', 'blankslate' ); ?><?php single_tag_title(); ?></h1>
  73.  
  74. <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  75.  
  76. <?php ajax_filter_get_posts (); ?>
  77.  
  78. <div class="tagged-posts"></div>
  79.  
  80. <?php endwhile; endif; ?>
  81.  
  82. </div>
  83.  
  84. </div>
  85.  
  86. </div>
  87.  
  88. <?php get_footer(); ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement