javascript - Exclude category from ajax filtering
I have category filters what display custom post types in categories. How to exclude specific category with ID from filtering?
I used 'category__not_in' => 12 but seems it not working with filters, only for hide posts what are in category 12.
Ajax for filters:
function filter_ajax() {
$category = $_POST['category'];
$args = array(
'post_type' => 'pozice',
'category__not_in' => 12,
'posts_per_page' => -1
);
if(isset($category)) {
$args['category__in'] = array($category);
}
$query = new WP_Query($args);
if($query->have_posts()) :
while($query->have_posts()) :
$query->the_post();
include("content_pozice_box.php");
endwhile;
endif;
wp_reset_postdata();
die();
}
JS:
(function($){
$(document).ready(function(){
$(document).on('click', '.js-filter-item > a', function(e){
e.preventDefault();
var category = $(this).data('category');
$.ajax({
url:wp_ajax.ajax_url,
data: { action: 'filter', category: category },
type: 'post',
success: function(result) {
$('.js-filter').html(result);
},
error: function(result) {
console.warn(result);
}
});
});
});
})(jQuery);
Function for display posts with filters in frontend:
function make_filters_shortcode($atts) {
?>
<div class="categories">
<ul>
<li class="js-filter-item"><a href="<?= home_url(); ?>">V??echny pozice</a></li>
<?php
$cat_args = array(
'exclude' => array(1),
'category__not_in' => 12,
'option_all' => 'V??echny pozice'
);
$categories = get_categories($cat_args);
foreach($categories as $cat) :
?>
<li class="js-filter-item"><a data-category="<?= $cat->term_id;?>" href="<?= get_category_link($cat->term_id); ?>"><?= $cat->name; ?></a></li>
<?php
endforeach;
?>
</ul>
</div>
<div class="js-filter hp">
<?php
$args = array(
'post_type' => 'pozice',
'category__not_in' => 12,
'posts_per_page' => 4
);
$query = new WP_Query($args);
if($query->have_posts()) :
while($query->have_posts()) :
$query->the_post();
include("content_pozice_box.php");
endwhile;
endif;
wp_reset_postdata();
?>
</div>
<?php
}
add_shortcode('job-filters', 'make_filters_shortcode');
Answer
Solution:
Can you please replace this category__not_in' => 12 with 'category__not_in' => array( 12 ).
Example code:
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category__not_in' => array( 55 )
);
$query = new WP_Query( $args );
?>
<?php
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
?>
// code
<?php
}
} else {
// no posts found
}
wp_reset_postdata();
?>
Source