0

I am creating a simple widget which displays all of the pages on the website. The trouble I am having is how to store the user's choice and display it on the front end. At the moment, when saving my widget options, the select box reverts back to the first page listed. I think I need to use WordPress' selected function?

Here is my code:

        <p>
        <label for="<?php echo $this->get_field_id('select'); ?>"><?php _e('Choose A Page:', 'check_avail_widget'); ?></label>
        <select name="<?php echo $this->get_field_name('select'); ?>" id="<?php echo $this->get_field_id('select'); ?>" class="widefat">

             <?php 
              $pages = get_pages(); 
                  foreach ( $pages as $page ) {
                    $option = '<option value="' . get_page_link( $page->ID ) . '">';
                        $option .= $page->post_title;
                        $option .= '</option>';
                        echo $option;
              }
             ?>

        </select>
    </p>

What do I need to add in order for this to work? Thanks in advance

1 Answer 1

0

Here's the working answer for future reference.

        <p>
        <label for="<?php echo $this->get_field_id('select'); ?>"><?php _e('Choose A Page:', 'check_avail_widget'); ?></label>
        <select name="<?php echo $this->get_field_name('select'); ?>" id="<?php echo $this->get_field_id('select'); ?>" class="widefat">

            <option value="Select A Page">
                <?php echo esc_attr( __('Select A Page') ); ?>
            </option>
            <?php
                $pages = get_pages();
                foreach ($pages as $page) { 
                    echo '<option value="'.get_page_link($page->ID).'" id="' . $page->post_title . '"', $select == get_page_link($page->ID) ? ' selected="selected"' : '', '>', $page->post_title, '</option>';
                    }
                ?>

        </select>
    </p>

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.