更新:看起来它们正在被保存,但当在admin中重新加载表单时(保存后),当前值不会显示在下拉框中。我有"选定"的行,但我不确定我缺少了什么,以便让它们显示当前值。
我正在尝试创建一个小部件,允许您从两个独立的下拉菜单中选择CTA和登录页。下拉列表是基于两种自定义帖子类型填充的,这两种类型运行良好。我的问题是,我不知道如何将值保存到数据库中(即,在管理员中单击小部件上的保存不会将值提交到数据库中。
以下是我的小部件类cta_widget中的相关函数。(我省略了第二个下拉列表的代码,因为它是相同的)。
<?php
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>
}
我想明白了。这是其他有相同问题的人的代码。
function form( $instance ) {
$cta = $instance['cta_id'];
$lp = $instance['lp_id'];
/* Set up some default widget settings. */
$defaults = array( 'cta_id' => '', 'lp_id' => '');
$instance = wp_parse_args( (array) $instance, $defaults );
?>
<p>
<?php echo 'CTA: '.$cta;?>
<?php echo 'LP: '.$lp.'<br/>';?>
<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->ID==$cta)
{
$is_selected = "selected = 'selected'";
}
else
{
$is_selected = "";
}
echo '<option value="' . $p->ID . '" '.$is_selected.'>' .$p->post_title . '</option>';
}
}
?>
</select>
</p>
<p>
<label for="<?php echo $this->get_field_name( 'lp_id' ); ?>"><?php _e( 'LP:' ); ?></label>
<select name="<?php echo $this->get_field_name( 'lp_id' ); ?>" id="<?php echo $this->get_field_name( 'lp_id' ); ?> style="width:100%;"">
<option value=""></option>
<?php
$posts = get_posts(
array(
'post_type' => 'locable_lps',
'numberposts' => -1
)
);
if($posts)
{
foreach( $posts as $p )
{
if ($p->ID==$lp)
{
$is_selected = "selected = 'selected'";
}
else
{
$is_selected = "";
}
echo '<option value="' . $p->ID . '" '.$is_selected.'>' .$p->post_title . '</option>';
}
}
?>
</select>
</p>
<?php
}