2

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.

2 Answers 2

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 )
1
  • Thank you, it worked like a charm! Commented Jan 29, 2020 at 11:58
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.