How to pass custom options from widget form to widget update callback?

I’ve added a few checkbox options to the default widget form. But I’m stuck on how to access these option states and pass them along during the widget save event (widget_update_callback) so that they can be saved by WP to the DB.

How do I pass my custom form values to WP to save as widget options for each widget?

Read More

In the first function, I’m Appending my checkbox options to all widgets control panels…

add_filter('in_widget_form', 'wse_widget_context_form');

function wse_widget_context_form(){

$checked = ' checked="checked"';
?>
<div class="wse_context">
    <ul>
        <li>Don't show this widget on: </li>
        <li><label><input value="on" type="checkbox" name="noHome" id="noHome"<?php if(isset($instance['noHome'])) echo $checked ?> />Home Page</label></li> 
        <li><label><input value="on" type="checkbox" name="noPosts" id="noPosts"<?php if(isset($instance['noPosts'])) echo $checked ?> /> Posts</label></li>
        <li><label><input value="on" type="checkbox" name="noPages" id="noPages"<?php if(isset($instance['noPages'])) echo $checked ?> /> Pages</label></li>
        <li><label><input value="on" type="checkbox" name="noCats" id="noCats"<?php if(isset($instance['noCats'])) echo $checked ?> /> Categories</label></li>
    </ul>
</div>

Callback function is below. $instance doesn’t contain the custom form values, only the default widget values (text and content). How do I append my custom options to $instance?

<?php
add_filter('widget_update_callback', 'wse_widget_context_callback');

function wse_widget_context_callback($instance){
    echo 'instance: '.$instance.'<br/>'; // returns array but no custom form values

}

Related posts

Leave a Reply

2 comments

  1. Not sure if you’re still struggling with this, but for anyone that is, here’s the solution:

    Add the following arguments to wse_widget_context_form(): $widget, $return and $instance

    Then use the following to get field IDs and field names: <?php echo $widget->get_field_id('field_name'); ?> and <?php echo $widget->get_field_name('field_name'); ?> respectively. e.g.

    <li><label><input value="on" type="checkbox" name="<?php echo $widget->get_field_name('noHome'); ?>" id="<?php echo $widget->get_field_id('noHome'); ?>"<?php if(isset($instance['noHome'])) echo $checked ?> />Home Page</label></li>
    

    Hope that helps!