I’m trying to use wp_category_checklist in a widget to display a list of checkboxes which, when saved, remain ticked. I’m having awful trouble at the moment getting them to save, as as far as I know it isn’t saving (the checkboxes remain unticked):-
Here’s the edited code I have at the moment.
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['widget_categories'] = $new_instance['post_category'];
return $instance;
}
function form($instance) {
$instance = wp_parse_args( (array) $instance, $default );
$categories = get_categories();
$category_array = $instance['widget_categories'];
if (!$category_array)
{
$category_array = array();
}
?>
<ul class="categorychecklist">
<?php wp_category_checklist(0,0, $category_array,false, NULL , false);?>
</ul>
<?php
}
Any ideas? Please let me know if you need anything else.
Thanks 🙂
The problem is that to make the
update
method of widget class work, the name inputs on theform
method should be set via$this->get_get_field_name('name_of_the_field');
butwp_category_checklist
has no argument to setup the name of the inputs (checkboxes).However,
wp_category_checklist
uses a walker class to print the checkboxes and allow customizing it. By default the class used isWalker_Category_Checklist
, and the method that prints the checkboxes isstart_el
.That method has no filter to allow editing of the input names, but we can create a custom walker, that accepts params to setup the name. If this walker extends
Walker_Category_Checklist
, we only need to overridestart_el
method (mostly copying from original).The code:
Now, probably in same file we can write the widget class:
Finally, register the widget: