Guest User

ajax categories

a guest
Jan 5th, 2016
250
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function ajax_filter_posts_scripts() {
  2. // Enqueue script
  3. wp_register_script('afp_script', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', false, null, false);
  4. wp_enqueue_script('afp_script');
  5.  
  6. wp_localize_script( 'afp_script', 'afp_vars', array(
  7. 'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
  8. 'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
  9. )
  10. );
  11. }
  12. add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
  13.  
  14. // Script for getting posts
  15. function ajax_filter_get_posts( $taxonomy ) {
  16.  
  17. // Verify nonce
  18. if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
  19. die('Permission denied');
  20.  
  21. $taxonomy = $_POST['taxonomy'];
  22.  
  23. // WP Query
  24. $args = array(
  25. 'category_name' => $taxonomy,
  26. 'post_type' => 'post',
  27. 'posts_per_page' => 10,
  28. );
  29.  
  30. // If taxonomy is not set, remove key from array and get all posts
  31. if( !$taxonomy ) {
  32. unset( $args['category_name'] );
  33. }
  34.  
  35. $query = new WP_Query( $args );
  36.  
  37. if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
  38.  
  39. <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
  40. <?php the_excerpt(); ?>
  41.  
  42. <?php endwhile; ?>
  43. <?php else: ?>
  44. <h2>No posts found</h2>
  45. <?php endif;
  46.  
  47. die();
  48. }
  49.  
  50. add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
  51. add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
  52.  
  53. //in my template file
  54. <?php
  55. $args = array(
  56. 'post_type' => 'post',
  57. 'posts_per_page' => 10,
  58. );
  59.  
  60. $query = new WP_Query( $args );
  61.  
  62. function tags_filter() {
  63. $tax = 'category';
  64. $terms = get_terms( $tax );
  65. $count = count( $terms );
  66.  
  67. if ( $count > 0 ): ?>
  68. <div class="post-tags">
  69. <?php
  70. foreach ( $terms as $term ) {
  71. $term_link = get_term_link( $term, $tax );
  72. echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> ';
  73. } ?>
  74. </div>
  75. <?php endif;
  76. }
RAW Paste Data