You need to enable JavaScript to run this app. 如何使用复选框按自定义分类法筛选WordPress自定义文章类型
优惠活动
大模型
产品
解决方案
定价
更多

如何使用复选框按自定义分类法筛选WordPress自定义文章类型

问题根源

  • 核心匹配错误:表单提交的是分类术语名称,查询时按术语ID匹配,二者无法对应,导致查询无结果
  • 参数校验缺失:未判断$_GET['course_types']是否存在,未勾选筛选选项时会抛出PHP警告,查询逻辑异常
  • 冗余参数:单分类条件查询不需要配置relation参数,该参数仅用于多个分类查询条件的逻辑关联

1. 修复复选框表单代码

<form method="GET">
<?php 
$terms = get_terms( array(
    'taxonomy' => 'course_types',
    'hide_empty' => false,
));
foreach($terms as $term) {
    // 修改value为term_id,和后续查询字段匹配
    echo '<label><input type="checkbox" name="course_types[]" value="' . $term->term_id . '">' . $term->name . '</label>';
} 
?>
<input type="submit" value="筛选">
</form>

2. 修复查询参数代码

<?php
$args = array(
    'post_type' => 'courses',
    'post_status' => 'publish', // 追加状态筛选,仅查询已发布的课程
);
// 仅在用户勾选了分类选项时追加分类查询条件
if (isset($_GET['course_types']) && !empty($_GET['course_types'])) {
    // 把字符串ID转成整型,规避SQL注入风险
    $course_type_ids = array_map('intval', $_GET['course_types']);
    $args['tax_query'] = array(
        array(
            'taxonomy' => 'course_types',
            'field' => 'term_id',
            'terms' => $course_type_ids,
            // 默认用IN:只要属于任意一个选中分类就返回,需要同时命中所有选中分类可改为AND
            'operator' => 'IN',
        )
    );
}
?>

3. 结果输出代码(可直接沿用)

$the_query = new WP_Query( $args );

// 循环输出内容
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        get_template_part( 'template-parts/content', 'courses' );
    }
} else {
    echo '暂无符合条件的课程';
}
// 重置文章数据
wp_reset_postdata();
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 06:27:04