WordPress setting with select - where is my mistake?

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.

Topic plugin-options select settings-api plugin-development options Wordpress

Category Web


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

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 )

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.