WordPress中如何将层级自定义分类法展示为多选复选框下拉菜单
实现方案
你现有代码存在两个核心问题:一是错误使用<select>标签包裹复选框(二者逻辑不兼容),二是只输出了一级父分类、没有处理层级子分类的渲染。以下是可直接使用的修复后代码,可实现带层级缩进的多选复选框效果:
完整功能代码
<label><strong>Building / Place Amenities</strong></label> <?php /** 要读取的自定义分类法别名 */ $taxonomy = "place_amenity_taxonomy"; /** 获取全部分类项 */ $terms = get_terms($taxonomy, array( "orderby" => "count", "hide_empty" => false )); /** 获取分类层级关系 */ $hierarchy = _get_term_hierarchy($taxonomy); /** 递归渲染分类复选框的函数 */ function render_term_checkboxes($term_id, $terms, $hierarchy, $level = 0) { // 匹配当前ID对应的分类项 foreach ($terms as $term) { if ($term->term_id == $term_id) { $current_term = $term; break; } } if (!isset($current_term)) return; // 按层级生成缩进 $indent = str_repeat(' ', $level); // 输出当前分类复选框,name设为数组格式保证可接收多个选中值 echo $indent . '<input type="checkbox" name="terms[]" value="' . esc_attr($current_term->term_id) . '" id="term-' . $current_term->term_id . '">'; echo '<label for="term-' . $current_term->term_id . '">' . esc_html($current_term->name) . '</label><br>'; // 递归渲染子分类 if (isset($hierarchy[$term_id]) && !empty($hierarchy[$term_id])) { foreach ($hierarchy[$term_id] as $child_term_id) { render_term_checkboxes($child_term_id, $terms, $hierarchy, $level + 1); } } } ?> <!-- 复选框容器 --> <div class="taxonomy-checkbox-list"> <?php // 从一级分类开始渲染 foreach ($terms as $term) { if ($term->parent == 0) { render_term_checkboxes($term->term_id, $terms, $hierarchy); } } ?> </div>
配套样式(可加入主题style.css)
.taxonomy-checkbox-list { margin: 12px 0; line-height: 2; } .taxonomy-checkbox-list input { margin-right: 6px; }
如果需要提交分类名称而非分类ID,可将input的value属性取值替换为$current_term->name即可
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

