Saturday, 24 August 2013

Custom Widget Not Saving Values to Database

Custom Widget Not Saving Values to Database

I'm trying to create a widget that will allow you to pick a CTA and a
Landing Page from two separate drop down menus. The drop downs are
populated based on two custom post types which is working fine. My problem
is that I can't figure out how to save the values to teh database (i.e.,
clicking save on the widget in the admin doesn't commit the values to the
database.
Here are the relevant functions from my widget class called cta_widget. (I
left out the code for the 2nd dropdown as it's identical).
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
/* Strip tags (if needed) and update the widget settings. */
$instance['cta_id'] = $new_instance['cta_id'];
$instance['url_id'] = $new_instance['url_id'];
return $instance;
}
function form( $instance ) {
/* Set up some default widget settings. */
$defaults = array( 'cta_id' => '23', 'url_id' => '28');
$instance = wp_parse_args( (array) $instance, $defaults );
?>
<p>
<label for="<?php echo $this->get_field_name( 'cta_id' );
?>"><?php _e( 'CTA:' ); ?></label>
<select name="<?php echo $this->get_field_name( 'cta_id' );
?>" id="cta_id<?php echo $this->get_field_name( 'cta_id' );
?>" style="width:100%;">
<option value=""></option>
<?php
$posts = get_posts(
array(
'post_type' => 'locable_ctas',
'numberposts' => -1
)
);
if($posts)
{
foreach( $posts as $p )
{
if ($p==$selected)
{
$selected = "selected = 'selected'";
}
else
{
$selected = "";
}
echo '<option value="' . $p->ID . '" '.$selected.'>'
.$p->post_title . '</option>';
}
}
?>
</select>
</p>
}

No comments:

Post a Comment