如何合法筛选父级层级分类下的Pods自定义文章?
解决方案
方法1:使用Pods短代码内置的taxonomy_parent参数
如果你的Pods短代码用于展示关联层级分类的内容,可直接通过taxonomy与taxonomy_parent参数组合筛选,无需复杂的where条件:
[pods name="你的Pods类型名称" taxonomy="cuisine" taxonomy_parent="european" template="你的模板名称"]
该参数会自动筛选出所有属于european父分类下的子分类关联的Pods条目。
方法2:在where参数中使用Pods内置的@get函数动态获取父分类ID
若必须通过where参数实现,可借助@get函数先获取父分类的term_id,再筛选父项匹配该ID的分类:
[pods name="你的Pods类型名称" where="cuisine.parent = @get(term,slug=european,term_id)" template="你的模板名称"]
@get(term,slug=european,term_id)会安全返回slug为european的分类ID,避免直接编写SQL触发安全限制。
方法3:自定义PHP函数封装筛选逻辑(适配复杂场景)
如果需要更灵活的控制,可在主题functions.php或自定义插件中添加以下函数,生成合法的子分类ID列表后传递给Pods短代码:
function get_child_term_ids_by_parent_slug($taxonomy, $parent_slug) { $parent_term = get_term_by('slug', $parent_slug, $taxonomy); if (!$parent_term) return ''; $child_terms = get_terms([ 'taxonomy' => $taxonomy, 'parent' => $parent_term->term_id, 'fields' => 'ids' ]); return implode(',', $child_terms); } // 注册短代码用于传递ID列表 add_shortcode('child_term_ids', function($atts) { $atts = shortcode_atts([ 'taxonomy' => 'cuisine', 'parent_slug' => 'european' ], $atts); return get_child_term_ids_by_parent_slug($atts['taxonomy'], $atts['parent_slug']); });
随后在Pods短代码中调用:
[pods name="你的Pods类型名称" where="cuisine.term_id IN ([child_term_ids parent_slug='european'])" template="你的模板名称"]
这种方式完全符合Pods安全规则,还可扩展处理多级分类等复杂需求。
内容的提问来源于stack exchange,提问作者Friedbert
相关产品推荐
相关产品推荐

