0

I'm trying to access widget information saved in the wp_options table.
I printed it out:

add_filter('the_content', function(){
    $res = get_option('widget_my_widget');
    print_r($res);
});

And it outputted this:

Array ( [2] => Array ( [title] => asian kung-fu generation [description] => awesome band ) [_multiwidget] => 1 )

My question: is the data always stored at index 2? If not, how can I access the data without worrying if it gives me the correct one or not?

2
  • What happens when you have two instances of the widget?
    – brasofilo
    Commented Jan 31, 2013 at 5:28
  • I tried it, and there's index 2 and then index 3 for the second instance. Commented Jan 31, 2013 at 5:44

1 Answer 1

1

It seems that the index value goes incrementing and we add/remove instances of the widget.

To make sure the correct data is grabbed, I can only think of checking inside the widget data itself through some control variable, something like:

Array ( 
    [2] => Array ( 
        [title] => asian kung-fu generation 
        [description] => awesome band 
        [var-of-control] => true (or some other convention) 
    ) 
    [_multiwidget] => 1 
)

Or even by title. The following function does this checking:

add_filter( 'the_content', function(){
    $res = get_option( 'widget_my_widget' );
    $check = check_array_key_value( $res, 'title', 'asian kung-fu generation' );
    print_r( $check );
});

function check_array_key_value( $array, $key, $val ) 
{
    foreach ( $array as $item )
    {       
        if ( isset( $item[$key] ) && $item[$key] == $val)
            return $item;
    }
    return false;
}

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.