WordPress.org

Forums

trying to save multiple select fields using update_options (2 posts)

  1. Derek Smart
    Member
    Posted 1 year ago #

    I need to display a list of all pages in a select field for a plugin I am developing. I want multiple pages to be able to be selected. I have been reading and reading, but still don't seem to get how this works. I am getting frustrated as this should be easy... :/

    I can get the selected fields to echo out, but they don't seem to be saving, i.e. when page is reloaded the selections are gone.

    the fields:

    <select id="exclude_page_from_cookies" name="exclude_page_from_cookies[]" multiple="multiple">
    			<?php
    
    			$pages = get_pages();
    			foreach ( $pages as $page ) {
    				$title = $page->post_title;
    				$id    = $page->id;
    				?>
    
    				<option id="<?php echo $id; ?>" value="<?php echo $title ?>" <?php selected( $title ); ?> >
    					<?php echo $title;?>
    				</option>
    			<?php
    			}
    			?>
    		</select>

    The save

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

    Thank you all in advance.

  2. Mark Waterous
    Member
    Posted 1 year ago #

    By looping through the array when you're saving the form submission, you're overwriting exclude_page_from_cookies multiple times, depending on how many pages were selected. This results in exclude_page_from_cookies only ever containing the last page in the array.

    Save the array as it's passed (short of any validation you want to run on it), then use in_array() to test selected().

    The form:

    <select id="exclude_pages_from_cookie" name="exclude_pages_from_cookie[]" multiple="multiple" accesskey="e">
        <?php
        $results = get_pages();
        $selected = get_option('exclude_pages_from_cookie', array());
    
        foreach ($results as $page):
            ?>
            <option value="<?php echo $page->post_name; ?>" <?php echo selected(in_array($page->post_name, $selected)); ?>>
                <?php echo $page->post_title; ?>
            </option>
            <?php
        endforeach;
        ?>
    </select>

    The save (without any error checking, don't forget to validate your data):

    if (array_key_exists('exclude_pages_from_cookie', $_POST)) {
        update_option( 'exclude_pages_from_cookie', $_POST['exclude_pages_from_cookie']);
    }

    I just noticed how old this post was. Oh well, responding anyway!

Topic Closed

This topic has been closed to new replies.

About this Topic