1

Problems:

The save works, but is only storing one of the options in the database after save.

Options not showing as selected after save.

The select fields:

<select id="exclude_page_from_cookies" name="exclude_page_from_cookies[]" multiple="multiple">
        <?php

        $pages = get_pages();
        foreach ( $pages as $page ) {
            $title = get_the_title($page);
            $id    = $page->id;
            ?>

            <option id="<?php echo $id; ?>" value="<?php echo $title ?>" <?php selected( $title ); ?> >
                <?php echo $title;?>
            </option>
        <?php
        }
        ?>
    </select>

The save function:

if ( isset( $_POST['exclude_page_from_cookies'] ) ) {
    foreach( $_POST['exclude_page_from_cookies'] as $exclude_page ) {
         echo $exclude_page;
         update_option( 'exclude_page_from_cookies', $exclude_page ) ;
    }
}

I understand I have already posted this in regular stack exchange, but since this is a WP thing I figured I'd move it here :)

1

First of all you need to save the value as an array because you want multiply items to be selected. The update_option function will serilized an array for you so you only need to give it an array of items. In your code you saving over all the items because you use the same key exclude_page_from_cookies and not as an array. You also need to mark the selected item as selected to be able to save more items. The function selected needs an selected and current to match and echo the selected tag. You save the value as the title but i recommend that you save it as the ID of the page, because if you have the ID you can easily get the title by using the function get_the_title(). So i updated your save function to accept arrays:

$exclude_pages = $_POST['exclude_page_from_cookies'];

if( isset( $exclude_pages ) ) 
{
   update_option( 'exclude_page_from_cookies', $exclude_pages );
}
else
{
   delete_option( 'exclude_page_from_cookies' );
}

And your selected box markup:

<select id="exclude_page_from_cookies" name="exclude_page_from_cookies[]" multiple="multiple">
       <?php
          $pages = get_pages();
          $exclude = get_option('exclude_page_from_cookies');

          foreach ( $pages as $page ) 
          {
          ?>
             <option value="<?php echo $page->ID; ?>" <?php echo ( in_array( $page->ID, $exclude ) ? 'selected' : '' ); ?> >
                <?php echo $page->post_title; ?>
             </option>
          <?php
          }
       ?>
    </select>
| improve this answer | |

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.