1

I'm trying to get a piece of code to filter out tags and categories when it generates its list. Right now it generates all posts by most recent (although it's a little buggy so if someone knows a better piece of code to use with ajax load more, I'm all ears.

Here's the code:

<div class="mcol-posts ajax-posts">
  <?php
    //BLOG POSTS
      $postsPerPage = 5;
      $args = array(
      'posts_per_page' => $postsPerPage
      $loop = new WP_Query($args);
      while ($loop->have_posts()) : $loop->the_post(); 
      get_template_part( 'template-parts/content', 'excerpt' );
      endwhile;
      wp_reset_postdata();                          
   ?>
</div>

I want to add something like this (could be different, but this is what I'm working with right now), in order to exclude any posts with tags or categories I don't want. It would be ideal to exclude more than one tag and more than one category, or to NULL either/both if not needed.

if ($cat_not_in) {
  $args['category__not_in'] = array($cat_not_in);
}
if ($tag_not_in) {
  $args['tag__not_in'] = array($tag_not_in);
}

1 Answer 1

0

I don't know how the structure of $cat_not_in looks like but make sure that that variable is not an array. If $cat_not_in is an array then you could try

if ($cat_not_in) {
  $args['category__not_in'] = $cat_not_in;
}
if ($tag_not_in) {
  $args['tag__not_in'] = $tag_not_in;
}

Also see WP Codex - WP_Query it allows for category exclusion by prefixing the category ID with a - (minus). Worth a try too. SO if your building your $cat_not_in array you could just prefix the IDs with - and then

if ($cat_not_in) {
  $args['cat'] = $cat_not_in;
}

Another approach completely might be to get a list of all category IDs into a $cat_get array and then iterate through the $cat_not_in array or string and pop the IDs you don't want off the $cat_get array then you can use the same code as above like this

if ($cat_not_in) {
  $args['cat'] = $cat_get;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.