我想用wp_dropdown_categories
在自定义小部件中。所有内容都显示得很好,但由于某些原因,无法正确保存。
这是form()
和update()
小部件的功能-我做错什么了吗?
public function form( $instance ) {
/* Set up some default widget settings. */
$defaults = array( \'title\' => \'Classes by Category\' );
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
<!-- Widget Title -->
<p>
<label for="<?php echo $this->get_field_id( \'title\' ); ?>">Title:</label>
<input type="text" id="<?php echo $this->get_field_id( \'title\' ); ?>" name="<?php echo $this->get_field_name( \'title\' ); ?>" value="<?php echo $instance[\'title\']; ?>" style="width:100%;" />
</p>
<!-- Categories Dropdown -->
<p>
<label for="<?php echo $this->get_field_id( \'cs-category\' ); ?>">Choose Class Category:</label>
<?php
$dropdown_args = array(
\'taxonomy\' => \'cs_categories\',
\'id\' => $this->get_field_id( \'cs-category\' ),
\'show_option_none\' => __( \'Select category\' ),
\'hide_empty\' => true,
\'hierarchical\' => true,
\'depth\' => 2,
\'echo\' => 0,
\'selected\' => $instance[ \'cs-category\' ],
\'class\' => \'widefat\'
);
echo wp_dropdown_categories( $dropdown_args );
?>
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[ \'title\' ] = strip_tags( $new_instance[ \'title\' ] );
$instance[ \'cs-category\' ] = filter_var( $new_instance[ \'cs-category\' ], FILTER_SANITIZE_NUMBER_INT );
return $instance;
}
我想在
update()
函数,我不确定如何获取要保存的字段。
我知道我可以get_terms
和aforeach
循环来构建下拉列表,但我想使用内置函数,因为它处理分层类别。
最合适的回答,由SO网友:obiPlabon 整理而成
您没有添加下拉列表/选择name
属性,这就是它不能按预期工作的原因。请尝试更新您的$dropdown_args
, 以下是更新的参数-
$dropdown_args = array(
\'taxonomy\' => \'cs_categories\',
\'id\' => $this->get_field_id( \'cs-category\' ),
\'name\' => $this->get_field_name( \'cs-category\' ), // Added this line
\'show_option_none\' => __( \'Select category\', \'text-domain\' ),
\'hide_empty\' => true,
\'hierarchical\' => true,
\'depth\' => 2,
\'echo\' => 0,
\'selected\' => $instance[ \'cs-category\' ],
\'class\' => \'widefat\'
);