如何在选择框选项中获取类别列表 [英] How to get category list in select box option

查看:25
本文介绍了如何在选择框选项中获取类别列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的控件中添加选项,例如 key =>;value 对所有可用选项的数组

I want to add options in my control like key => value pair array of all available options

像这样:

$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,
        ]
);

但是为了代替标题描述和按钮,我想拥有我帖子的所有类别,所以我编写了一个函数 my_cat

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

function my_cat() {
    $categories = get_categories();
    echo '[';
    foreach ($categories as $category) :

        echo $category->term_id . '=>' . $category->name . ',';

    endforeach;
    echo ']';
}

我将它用于选项

$this->add_control('show_elements', [
    'label' => __('Show Elements', 'your-plugin'),
    'type' => Controls_Manager::SELECT2,
    'options' => my_cat(),
    'multiple' => true,
        ]
);

但是我没有得到类别列表的选项,my_cat 函数有什么问题吗?

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:

function my_cat() {
    $categories = get_categories();
    $cat_array = [];
    foreach ($categories as $category) :
        $cat_array[$category->term_id] = $category->name;
    endforeach;
    return $cat_array;
}

为了正确地做到这一点,我们希望 choices 采用这种形式的关联数组:

To do this correctly, in opinion, we want choices to take associative array in this form:

$this->add_control('show_elements', [
    'label' => __('Show Elements', 'your-plugin'),
    'type' => Controls_Manager::SELECT2,
    'choices' => my_cat(), //<-- Check this line.
    'multiple' => true,
        ]
);

参考:添加控件

希望这会有所帮助!

这篇关于如何在选择框选项中获取类别列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆