How to get category list in select box option

2019-09-17 10:09发布

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

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

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 ?

标签: php wordpress
1条回答
贪生不怕死
2楼-- · 2019-09-17 10:28

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;
}

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

Reference: add control

Hope this helps!

查看更多
登录 后发表回答