I have a widget where there is a select dropdown, with a list of all the pages on the site. I am trying to get my code correct so that when a user chooses a page, after clicking Save in the widget, the select box doesn't revert back to 'Select a page' value.

This is the snippet I have now but it's not working correctly. There are no errors being displayed either. Any help would be welcome. Thanks

<label for="<?php echo $this->get_field_id('read_more_link'); ?>"><?php _e('Read More Link', 'iw_widget_plugin'); ?></label>

<select name="<?php echo $this->get_field_name('read_more_link'); ?>" id="<?php echo $this->get_field_id('read_more_link'); ?>" class="widefat">

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

  • When you inspect the HTML after saving, does the option that is supposed to be selected have the selected="selected" attribute? (I suspect that the evaluation of $read_more_link == $page ? ' selected="selected"' : '' isn't working the way you think it should). – Jared Cobb Aug 3 '14 at 14:54
  • Also I think that code have some error. Why you're adding '$' sign before the get_page_link() function? – Chinmoy Kumar Paul Aug 3 '14 at 14:55
  • I've removed the '$' from in front of get_page_link(), thanks for spotting that. – Huw Rowlands Aug 3 '14 at 15:01
  • To answer @JaredCobb; When I select a page from the dropdown list, I then click Save, and it reverts back to the default Select A Page. Looking at the code using Dev Tools, there is no 'selected' code added. – Huw Rowlands Aug 3 '14 at 15:03
  • modify the code little bit. I think that it will work ( ($read_more_link == get_page_link($page->ID) ) ? ' selected="selected"' : '') – Chinmoy Kumar Paul Aug 3 '14 at 15:06

Your Answer

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

Browse other questions tagged or ask your own question.