如何在PHP数组中插入变量自动生成CPT筛选分类?
问题描述
我给自定义文章类型(CPT)设置了一个筛选器,目前需要手动在array()中填写所有自定义分类名称:
sc_render_filter( 'test', 'All Categories', array( 'Category One', 'Category two', 'Category three'), '' . ($current_sub_brand ? ( 'sub_brand=' . $current_sub_brand . '&' ) : '' ) . ($current_varietal ? ( 'varietal=' . $current_varietal . '&' ) : '' ) . ($current_publication ? ( 'publication=' . $current_publication . '&' ) : '' ) . ($current_vintage ? ( 'vintage=' . $current_vintage . '&' ) : '' ) );
请问能否在array()中使用变量或foreach循环自动生成分类项名称?或是需要采用其他方法?以下是我编写的foreach循环代码:
$source = ''; foreach ($termslist as $term) { $source .= "'". $term->name. "'". ','; } echo rtrim($source, ',');
解决方案
当然可以自动生成分类数组,你之前的字符串拼接方式没必要,而且无法直接满足sc_render_filter对数组参数的要求,直接构建PHP数组即可:
方法1:foreach循环构建数组
初始化空数组,遍历分类术语后将名称存入数组:
// 初始化空数组 $category_names = []; // 遍历分类术语列表 foreach ($termslist as $term) { $category_names[] = $term->name; } // 将生成的数组传入筛选器函数 sc_render_filter( 'test', 'All Categories', $category_names, // 替换原手动填写的数组 '' . ($current_sub_brand ? ( 'sub_brand=' . $current_sub_brand . '&' ) : '' ) . ($current_varietal ? ( 'varietal=' . $current_varietal . '&' ) : '' ) . ($current_publication ? ( 'publication=' . $current_publication . '&' ) : '' ) . ($current_vintage ? ( 'vintage=' . $current_vintage . '&' ) : '' ) );
方法2:array_map简化代码
如果$termslist是WP_Term对象数组,可以用array_map一行完成数组生成,代码更简洁:
$category_names = array_map(function($term) { return $term->name; }, $termslist); // 同样将$category_names传入sc_render_filter即可 sc_render_filter(/* 其他参数保持不变,第三个参数替换为$category_names */);
补充说明
- 你之前的字符串拼接方式生成的是字符串格式的分类列表,但
sc_render_filter的第三个参数要求是PHP数组类型,直接传拼接后的字符串会报错,必须传入真正的数组。 - 如果还没获取到
$termslist,可以通过get_terms()获取自定义分类的术语,示例代码如下(替换为你的自定义分类slug):
$termslist = get_terms(array( 'taxonomy' => 'your_custom_taxonomy_slug', 'hide_empty' => false, // 是否隐藏无关联文章的分类,按需设置 ));
内容的提问来源于stack exchange,提问作者Natalya
相关产品推荐
相关产品推荐

