How to access widget data from outside widget?

First, there is no such thing as a widget’s data. This is because a widget may be included in several places on a site. So the data belongs not to the widget, but to the instance of that widget. For this reasons, every widget gets an ID. If you want to know what the ID of a widget instance is, you can use this code to display it in the backend.

add_action('in_widget_form', 'wpse240327_get_widget_id');

function wpse240327_get_widget_id($widget_instance) {
    if ($widget_instance->number=="__i__"){
        echo '<p class="widget-id-message">' . __('Save the widget to get its ID','textdomain') . '</p>';
        }
    else {
        echo '<p class="widget-id-message">' . __('The widget ID is:','textdomain') . ' ' . $widget_instance->id . '</p>';
        }
    }

Beware that if you remove the widget from the sidebar and later place it back again, the ID may have changed. In any case, to identify a specific widget instance, you need this ID. The ID has two components: a name and a number, which you both will need:

my_widget_name_777

Let’s split that:

$widget_name="my_widget_name";
$widget_instance="777";

Now, you will need to access the array that stores all the data. Every widget has its own option, which holds an array of all the instances of that particular widget. You access it like this:

$widget_instances = get_option('widget_' . $widget_name);

This gives you an array with instances the keys are formed by the number, so you will get your data at:

$data = $widget_instances[$widget_instance];

Leave a Comment