2

I’m trying to access a widget’s option settings from outside the widget code.

The name of the widget is: category_grid, and the name of the is: widget_categories.

I tried the following code which was suggested in an answer to a question on another site but it doesn’t return anything:

<?php
$options = get_option( 'widget_category_grid' );
$cats = $options['widget_categories'];
echo $cats;
?>
0

1 Answer 1

3

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];
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.