如何在选择框选项中获取类别列表

时间:2017-01-14 14:56:39

标签: php wordpress

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

像这样:

$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

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函数有什么问题吗?

1 个答案:

答案 0 :(得分:1)

尝试将此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;
}

为了正确地做到这一点,我们希望choices能够以这种形式获取关联数组:

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

参考:add control

希望这有帮助!