I have a wordpress widget where im saving the options, Title + Copy + URL
The url is generated by listing the wordpress pages
The below code saves and works fine on the front end. But in the widget settings panel when you save it reverts back to select page, i need it to display the previously selected item that it saved.
// Sidebar CTA Widget
class SidebarCTAWidget extends WP_Widget {
function SidebarCTAWidget() {
$widget_ops = array('classname' => 'SidebarCTAWidget', 'description' => 'Editable Sidebar CTAs' );
$this->WP_Widget('SidebarCTAWidget', 'Sidebar Call to Action', $widget_ops);
}
function form($instance) {
$defaults = array( 'title' => '', 'copy' => '', 'url' => '');
$instance = wp_parse_args( (array) $instance, $defaults );
$title = $instance['title'];
$copy = $instance['copy'];
$url = $instance['url'];
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">Title:
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('copy'); ?>">Copy:
<textarea rows="5" class="widefat" name="<?php echo $this->get_field_name( 'copy' ); ?>" / ><?php echo esc_attr( $copy ); ?></textarea>
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id('url'); ?>">URL:
<select class="widefat" id="<?php echo $this->get_field_id('url'); ?>" name="<?php echo $this->get_field_name('url'); ?>" name="page-dropdown">
<option value=""> <?php echo esc_attr( __( 'Select Page' ) ); ?></option>
<?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>
</label>
</p>
<?php }
//save the widget settings
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['copy'] = strip_tags( $new_instance['copy'] );
$instance['url'] = strip_tags( $new_instance['url'] );
return $instance;
}
function widget($args, $instance){
extract($args, EXTR_SKIP);
echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
$copy = empty($instance['copy']) ? ' ' : apply_filters('widget_title', $instance['copy']);
$url = empty($instance['url']) ? ' ' : apply_filters('widget_title', $instance['url']);
if (!empty($title))
echo '<div class="clearfix sidebar-content"><h3>' . $title . '</h3>';
;
// This is the HTML
echo '<p>' . $copy . '</p></div>';
echo '<p class="sidebar-link"><a href="' . $url . '" title="Find out more">Find Out More</a></p>';
// END
echo $after_widget;
}
}
add_action( 'widgets_init', create_function('', 'return register_widget("SidebarCTAWidget");') );
Thanks to the help of @b__ i managed to work out how to compare the saved url in the database and mark it as selected