[英]How to get category list in select box option
I want to add options in my control like key => value
pair array of all available options 我想在控件中添加所有可用选项的key => value
对数组之类的选项
Like this: 像这样:
$this->add_control('show_elements', [
'label' => __('Show Elements', 'your-plugin'),
'type' => Controls_Manager::SELECT2,
'options' => [
'title' => __('Title', 'your-plugin'),
'description' => __('Description', 'your-plugin'),
'button' => __('Button', 'your-plugin'),
],
'multiple' => true,
]
);
But in place of title description and button I want to have all the categories of my post so I write a function my_cat
但是我想使用标题的所有类别来代替标题说明和按钮,所以我编写了一个函数my_cat
function my_cat() {
$categories = get_categories();
echo '[';
foreach ($categories as $category) :
echo $category->term_id . '=>' . $category->name . ',';
endforeach;
echo ']';
}
And I use it for options 我用它来做选择
$this->add_control('show_elements', [
'label' => __('Show Elements', 'your-plugin'),
'type' => Controls_Manager::SELECT2,
'options' => my_cat(),
'multiple' => true,
]
);
But I'm not getting option with category list, is there anything wrong with my_cat
function ? 但是我没有类别列表选项, my_cat
函数有什么问题吗?
Try by replacing you my_cat()
with this: 尝试用以下代码替换my_cat()
:
function my_cat() {
$categories = get_categories();
$cat_array = [];
foreach ($categories as $category) :
$cat_array[$category->term_id] = $category->name;
endforeach;
return $cat_array;
}
To do this correctly, in opinion, we want choices
to take associative array in this form: 鉴于此,正确地做到这一点,我们希望choices
采用这种形式的关联数组:
$this->add_control('show_elements', [
'label' => __('Show Elements', 'your-plugin'),
'type' => Controls_Manager::SELECT2,
'choices' => my_cat(), //<-- Check this line.
'multiple' => true,
]
);
Reference: add control 参考: 添加控件
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.