Home > OS >  How to AJAX filter "All news"
How to AJAX filter "All news"

Time:08-18

I implement AJAX filtering by news taxonomies. I am following the example from the site. Now I have implemented filtering by two taxonomies, but I still need to implement filtering so that all the news are shown. How can i do this?

filters:

<ul >
  <li >
    <a  href="javascript:void(0);" data-slug="">All News</a>
  </li>
  <li >
    <ul >
      <?php foreach ($genress_terms as $term): ?>
      <li>
        <a  href="javascript:void(0);" data-slug="<?= $term->slug; ?>">
          <?= $term->name; ?>
        </a>
      </li>
      <?php endforeach; ?>
    </ul>
  </li>
  <li >
    <ul >
      <?php foreach ($year_terms as $term): ?>
      <li>
        <a  href="javascript:void(0);" data-slug="<?= $term->slug; ?>">
          <?= $term->name; ?>
        </a>
      </li>
      <?php endforeach; ?>
    </ul>
  </li>
</ul>

AJAX:

 $('.filter-list_item').on('click', function() {
  $('.filter-list_item').removeClass('active');
  $(this).addClass('active');

  $.ajax({
    type: 'POST',
    url: '/wp-admin/admin-ajax.php',
    dataType: 'html',
    data: {
      action: 'filter_news',
      category: $(this).data('slug'),
    },
    success: function(res) {
      $('.news-list').html(res);
    }
  })
});

function.php:

function filter() {
  $taxSlug = $_POST['category'];

  $ajaxposts = new WP_Query([
    'post_type' => 'news',
    'posts_per_page' => -1,
    'tax_query' => array(
      'relation' => 'OR',
      array(
        'taxonomy' => 'genres',
        'field' => 'slug',
        'terms' => $taxSlug
      ),
      array(
        'taxonomy' => 'years',
        'field' => 'slug',
        'terms' => $taxSlug
      ),
    )
  ]);

CodePudding user response:

Build the array which you pass to WP_Query with a condition that if the $_POST['category'] is empty then don't add the tax_query element to the array

<?php
function filter() {
  
  $query = [
    'post_type' => 'news',
    'posts_per_page' => -1
  ];
  
  $taxSlug = $_POST['category'] ?? '';
  
  if ($taxSlug) {
      $query['tax_query'] = [
        'relation' => 'OR',
        [
            'taxonomy' => 'genres',
            'field' => 'slug',
            'terms' => $taxSlug
        ],
        [
            'taxonomy' => 'years',
            'field' => 'slug',
            'terms' => $taxSlug
        ]
    ];
  }

  $ajaxposts = new WP_Query($query);
}
  • Related