Advertisement
Guest User

Untitled

a guest
Jan 9th, 2022
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. HTML / PHP
  2.  
  3. <section id="info">
  4. <div class="container">
  5.  
  6. <?php $categories = get_categories(); ?>
  7. <ul class="cat-list">
  8. <li>
  9. <a class="cat-list_item active" href="#!" data-slug="">All projects</a>
  10. </li>
  11.  
  12. <?php foreach($categories as $category) : ?>
  13. <li>
  14. <a class="cat-list_item" href="#!" data-slug="<?= $category->slug; ?>">
  15. <?= $category->name; ?>
  16. </a>
  17. </li>
  18. <?php endforeach; ?>
  19. </ul>
  20.  
  21. <?php
  22. $posts = new WP_Query([
  23. 'posts_per_page' => -1,
  24. 'order_by' => 'date',
  25. 'order' => 'desc',
  26. ]);
  27. ?>
  28.  
  29. <?php if($posts->have_posts()): ?>
  30. <ul class="project-tiles">
  31. <?php
  32. while($posts->have_posts()) : $posts->the_post();
  33. include('components/project-list-item.php');
  34. endwhile;
  35. ?>
  36. </ul>
  37. <?php wp_reset_postdata(); ?>
  38. <?php endif; ?>
  39.  
  40. </div>
  41. </section>
  42.  
  43.  
  44.  
  45. JS / JQuery
  46.  
  47. jQuery(function($){
  48. $.ajax({
  49. type: 'POST',
  50. url: '/wp-admin/admin-ajax.php',
  51. dataType: 'html',
  52. data: {
  53. action: 'filter_posts',
  54. category: $(this).data('slug'),
  55. type: $(this).data('type'),
  56. },
  57. success: function(res) {
  58. $('.project-tiles').html(res);
  59. }
  60. });
  61. });
  62.  
  63. $('.cat-list_item').on('click', function(e) {
  64. e.preventDefault();
  65. console.log('clicked');
  66. $('.cat-list_item').removeClass('active');
  67. $(this).addClass('active');
  68. });
  69.  
  70.  
  71.  
  72. Functions.php
  73.  
  74. // AJAX filter for projects
  75. function filter_posts() {
  76. $catSlug = $_POST['category'];
  77.  
  78. $ajaxposts = new WP_Query([
  79. 'posts_per_page' => -1,
  80. 'category_name' => $catSlug,
  81. 'orderby' => 'date',
  82. 'order' => 'desc',
  83. ]);
  84. $response = '';
  85.  
  86. if($ajaxposts->have_posts()) {
  87. while($ajaxposts->have_posts()) : $ajaxposts->the_post();
  88. $response .= get_template_part('components/project-list-item');
  89. endwhile;
  90. } else {
  91. $response = 'empty';
  92. }
  93.  
  94. echo $response;
  95. exit;
  96. }
  97. add_action('wp_ajax_filter_posts', 'filter_posts');
  98. add_action('wp_ajax_nopriv_filter_posts', 'filter_posts');
  99.  
  100.  
  101.  
  102.  
  103.  
  104.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement