Create variable from widget instance

Where are the widgets settings stored?

The widget settings are stored in the wp_options table. You can retrieve it with

print_r( get_option( 'widget_x' ) );

where x is the $id_base input parameter of the WP_Widget class constructor. If $id_base is empty, then it uses the widget class name in lower case letters, without the prefixes: wp_widget or widget_.

Here’s an example:

class WP_Widget_Categories extends WP_Widget {

        function __construct() {
                $widget_ops = array( 'classname' => 'widget_categories', 'description' => __( "A list or dropdown of categories." ) );
                parent::__construct('categories', __('Categories'), $widget_ops);
        }

You can see how the corresponding option name is created, here in the WP_Widget class constructor:

function __construct( $id_base, $name, $widget_options = array(), $control_options = array() ) {
            $this->id_base = empty($id_base) ? preg_replace( '/(wp_)?widget_/', '', strtolower(get_class($this)) ) : strtolower($id_base);
            $this->name = $name;
            $this->option_name="widget_" . $this->id_base;
            $this->widget_options = wp_parse_args( $widget_options, array('classname' => $this->option_name) );
            $this->control_options = wp_parse_args( $control_options, array('id_base' => $this->id_base) );
    }

where the save settings method is:

   function save_settings($settings) {
            $settings['_multiwidget'] = 1;
            update_option( $this->option_name, $settings );
    }

Example:

Widget class name      | Option name
------------------------------------------
WP_Widget_Text         | widget_text
WP_Widget_Archives     | widget_archives
WP_Widget_Calendar     | widget_calendar
WP_Widget_Search       | widget_search    
WP_Widget_Tag_Cloud    | widget_tag_cloud
WP_Widget_Categories   | widget_categories
WP_Widget_Recent_Posts | widget_recent-posts
My_Widget              | widget_my_widget

... etc

For multi widgets the option value is an array with instance numbers as array keys.

Example: Text widgets

To retrieve all the saved data from the text widgets, we can use:

print_r( get_option( 'widget_text' ) );

and get for example the following output:

Array(

   [1] => Array
        (
            Create variable from widget instance => Bacon Ipsum
            [text] => Bacon ipsum dolor sit amet t-bone shankle landjaeger, turkey meatloaf shank swine jowl jerky doner kielbasa salami ham. 
            [filter] => 
        )
   [3] => Array
        (
            Create variable from widget instance => Lorem Ipsum
            [text] => Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
            [filter] => 
        )

    [_multiwidget] => 1
)

I hope this helps.

Leave a Comment