最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugin development - WordPress setting with select - where is my mistake?

programmeradmin1浏览0评论

I have two option callbacks in my plugin, one with a ckeckbox and one with a select field. The first one is working perfectly, the second not. The select field doesn't save its value. I double checked the code which registers the two settings, I assume my mistake is somewhere in the callback.

Any ideas?

Checkbox (works):

public function myplugin_post_menu_cb() {
    echo '<input type="checkbox" name="' . $this->option_name . '_post_menu' . '" value="1" "' . checked(1, get_option('myplugin_post_menu'), false) . '" />';
}

Select (doesn't work):

public function myplugin_admin_bar_cb() {
    echo '<select name="' . $this->option_name . '_admin_bar' . '">';
        echo '<option value="1" "' . selected( get_option('myplugin_admin_bar'), 1 ) . '">1</option>';
        echo '<option value="2" "' . selected( get_option('myplugin_admin_bar'), 2 ) . '">2</option>';
    echo '</select>';
}

Thanks for the help.

I have two option callbacks in my plugin, one with a ckeckbox and one with a select field. The first one is working perfectly, the second not. The select field doesn't save its value. I double checked the code which registers the two settings, I assume my mistake is somewhere in the callback.

Any ideas?

Checkbox (works):

public function myplugin_post_menu_cb() {
    echo '<input type="checkbox" name="' . $this->option_name . '_post_menu' . '" value="1" "' . checked(1, get_option('myplugin_post_menu'), false) . '" />';
}

Select (doesn't work):

public function myplugin_admin_bar_cb() {
    echo '<select name="' . $this->option_name . '_admin_bar' . '">';
        echo '<option value="1" "' . selected( get_option('myplugin_admin_bar'), 1 ) . '">1</option>';
        echo '<option value="2" "' . selected( get_option('myplugin_admin_bar'), 2 ) . '">2</option>';
    echo '</select>';
}

Thanks for the help.

Share Improve this question asked Jan 26, 2020 at 18:00 t3chernobylt3chernobyl 315 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

The problem is that in your calls to selected() you haven't set the 3rd parameter to false. For both selected() and checked() if you don't do this it will echo the attribute immediately, which won't work properly if you're using it inside a concatenated string.

So change:

selected( get_option('myplugin_admin_bar'), 1 )

To:

selected( get_option('myplugin_admin_bar'), 1, false )

Problem solved! Here is the full code, if anyone is interested:

public function myplugin_admin_bar_cb() {
    echo '<select name="' . $this->option_name . '_admin_bar' . '">';
        echo '<option value="1" ' . selected(1, get_option('myplugin_admin_bar'), false ) . '>On</option>';
        echo '<option value="2" ' . selected(2, get_option('myplugin_admin_bar'), false ) . '>Off</option>';
    echo '</select>';       
}
发布评论

评论列表(0)

  1. 暂无评论