You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress Ajax分类筛选中排除指定ID的分类?

解决WordPress自定义文章类型筛选器排除指定分类的问题

问题核心

你使用category__not_in => 12能隐藏该分类下的文章,但无法在筛选器的分类列表中排除ID12的分类,原因是:

  • category__not_in是WP_Query的专属参数,get_categories()不支持这个参数,要排除分类列表里的项,必须使用get_categories原生的exclude参数。

具体修改方案

1. 修正前端筛选器的分类查询逻辑

把短代码函数里的$cat_args参数修改,将ID12加入exclude数组,删除无效的category__not_in:

$cat_args = array(
    'exclude' => array(1, 12), // 把所有要排除的分类ID放在这个数组里
    'option_all' => 'Všechny pozice'
);

2. 加固AJAX查询的安全性(可选但推荐)

虽然前端已经隐藏了ID12的分类,但可以在AJAX函数中增加判断,防止恶意请求传入ID12:

function filter_ajax() {
    // 验证参数并转成整数,避免SQL注入风险
    $category = isset($_POST['category']) ? intval($_POST['category']) : '';
    
    $args = array(
        'post_type' => 'pozice',
        'category__not_in' => 12,
        'posts_per_page' => -1
    );
    
    // 仅处理非ID12的分类请求
    if($category && $category != 12) {
        $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();
}

3. 保留原有文章查询的设置

短代码里初始展示文章的查询(.js-filter容器内)已经正确使用category__not_in =>12,这个设置无需修改,它会确保默认展示的内容不包含ID12分类下的文章。


修正后的完整短代码函数

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, 12), // 合并需要排除的分类ID
        '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');

内容的提问来源于stack exchange,提问作者JohnK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 01:25:39