问题是update
widget类工作的方法,在form
方法应通过设置$this->get_get_field_name(\'name_of_the_field\');
但是wp_category_checklist
没有设置输入名称的参数(复选框)。
然而wp_category_checklist
使用walker类打印复选框并允许对其进行自定义。默认情况下,使用的类为Walker_Category_Checklist
, 打印复选框的方法是start_el
.
该方法没有允许编辑输入名称的过滤器,但我们可以创建一个自定义的walker,它接受params来设置名称。如果这个助行器伸出Walker_Category_Checklist
, 我们只需要覆盖start_el
方法(主要是从原件复制)。
代码:
// This is required to be sure Walker_Category_Checklist class is available
require_once ABSPATH . \'wp-admin/includes/template.php\';
/**
* Custom walker to print category checkboxes for widget forms
*/
class Walker_Category_Checklist_Widget extends Walker_Category_Checklist {
private $name;
private $id;
function __construct( $name = \'\', $id = \'\' ) {
$this->name = $name;
$this->id = $id;
}
function start_el( &$output, $cat, $depth = 0, $args = array(), $id = 0 ) {
extract( $args );
if ( empty( $taxonomy ) ) $taxonomy = \'category\';
$class = in_array( $cat->term_id, $popular_cats ) ? \' class="popular-category"\' : \'\';
$id = $this->id . \'-\' . $cat->term_id;
$checked = checked( in_array( $cat->term_id, $selected_cats ), true, false );
$output .= "\\n<li id=\'{$taxonomy}-{$cat->term_id}\'$class>"
. \'<label class="selectit"><input value="\'
. $cat->term_id . \'" type="checkbox" name="\' . $this->name
. \'[]" id="in-\'. $id . \'"\' . $checked
. disabled( empty( $args[\'disabled\'] ), false, false ) . \' /> \'
. esc_html( apply_filters( \'the_category\', $cat->name ) )
. \'</label>\';
}
}
现在,我们可以在同一个文件中编写widget类:
/**
* An example of widget using wp_category_checklist on form
*/
class TestCategoryWidget extends WP_Widget {
function __construct(){
parent::__construct( false, \'TestWidget\');
}
function widget( $args, $instance ) {
// Displays the widget on frontend
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[\'widget_categories\'] = $new_instance[\'widget_categories\'];
return $instance;
}
function form( $instance ) {
$defaults = array( \'widget_categories\' => array() );
$instance = wp_parse_args( (array) $instance, $defaults );
// Instantiate the walker passing name and id as arguments to constructor
$walker = new Walker_Category_Checklist_Widget(
$this->get_field_name( \'widget_categories\' ),
$this->get_field_id( \'widget_categories\' )
);
echo \'<ul class="categorychecklist">\';
wp_category_checklist( 0, 0, $instance[\'widget_categories\'], FALSE, $walker, FALSE );
echo \'</ul>\';
}
}
最后,注册小部件:
function TestCategoryWidgetInit() {
register_widget( \'TestCategoryWidget\' );
}
add_action( \'widgets_init\', \'TestCategoryWidgetInit\' );