0

How can I register or add multiple options into one field. For example, we save a logo in get_options() by registering the setting and adding fields by add_settings_field() function and we output it accordingly.

But what if we want to save multiple options into one field, like we have an option on our page called "Select your favourite colour" and there are check-boxes with different colours and user needs to select multiple colours (not a single colour) then how would we save that in WordPress options and how to output it too?

  • 2
    The API can handle an array but you need to show us some code. – Wyck Feb 7 '14 at 1:12
0

Just set the name attribute in your checkbox tag in the format like: favourite_colors[]. The following code is derived from this thread.

add_settings_field(  
    'favourite-colors',  
    'Select your favourite colour',  
    'favourite_colors_checkbox_callback',  
    'my-settings'
);

function favourite_colors_checkbox_callback() {

    $options = get_option( 'favourite_colors' );

    $html = '<input type="checkbox" id="red" name="favourite_colors[red]" value="1"' . checked( 1, $options['red'], false ) . '/>';
    $html .= '<label for="red">Red</label><br />';
    $html = '<input type="checkbox" id="yellow" name="favourite_colors[yellow]" value="1"' . checked( 1, $options['yellow'], false ) . '/>';
    $html .= '<label for="yellow">Yellow</label>';

    echo $html;

}
  • Thank you for the quick response 1fixdotio but the code you gave isn't working. It is still showing one checkbox infront of the field Select your favourite colour. What I am trying to develop is a wordpress plugin which will restrict the content and of course for that I planned to save each page against each user using settings api. This is the code which will give you an idea. The code is in the next comment – Usman Ali Feb 7 '14 at 8:30
  • $users = get_users(); foreach ( $users as $user ) { add_settings_field($user->user_login, $user->user_login, function ($args) { $value = esc_attr( $args['value'] ); $pages = get_pages(); foreach ( $pages as $page ) { echo '<input type="checkbox" id="'.$page->ID.'-'.$value.'" name="save-options['.$value.']" value="'.$page->ID.'-'.$value.'" />' . $page->post_title; } }, 'ua_par_settings', 'par_main_section', array( 'value' => $user->user_login, – Usman Ali Feb 7 '14 at 8:32
  • Sorry my answer didn't help. Could you update your code to your question? So others could get a clear picture to help you. – 1fixdotio Feb 7 '14 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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