Changing widget options via the functions.php when there are no hooks

After some digging, I’ve arrived at a solution (explained in the comments) –

function change_widget_configuration() {

$options = get_option('widget_some-widget'); // retrieve the options for all occurrences of the named widget*

    $widget_number = 3; // the id number of the specific occurrence of the widget whose options you wish to alter (this can be obtained simply in the html from the <div id=""> tag of the specific widget)

    $sub_options = $options[$widget_number]; // this now contains the options of the specific occurrence of the widget**

        $sub_options['some_name'] = 'new value'; // change any named option*
        $sub_options['some_other_name'] = 'new value';

    $options[$widget_number] = $sub_options // pass the changes back to the multi-widget array

update_option('widget_some-widget', $options); // write the altered widget options back into the wp_options table*

}

*Add appropriate conditional statements to check that the options exist before getting or updating the array.

**This is the particular solution for multiwidgets.

That’s it! This simple little function now allows us to control the output of all sorts of widgets, simply by changing their options programmatically, rather than manually or hacking into the code. For example, I now have a third-party widget on the Frontpage of a blog, which normally displays a list of posts from a fixed category set in admin, but which now has its category (and its title) changing periodically according to a custom function placed in functions.php. The possible applications are endless, and it solves many of the problems of interacting with plugins which lack useful hooks, all without having to hack into their code. Add custom fields to the mix and we’re flying…

Leave a Comment