6

I'm trying to access the $instance variable from a custom function I've written inside my Widget, but I keep getting a "variable is undefined" error.

How can I re-create the $instance variable?

public function __construct() {

    parent::__construct(
        'cst_twitter_widget',
        __( 'CST Twitter Tweets', 'chicagosuntimes' ),
        array(
            'description' => __( 'Displays Tweets from a given list url.', 'mythemename' ),
        )
    );

    add_action( 'wp_head', array( $this, 'cst_twitter_feed_ajaxurl' ) );
    add_action( 'wp_ajax_refresh_tweets', array( $this, 'refresh_tweets' ) );

}

/**
 * Set the AJAX URL for the Twitter Feed Widget
 */
public function cst_twitter_feed_ajaxurl() {
?>
    <script type="text/javascript">
    var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    </script>
<?php
}

/**
 * Display the updated Twitter Feed
 */
public function refresh_tweets() {

    //my custom function, where i'm trying to re-create the $instance and access the values
    $instance = self::$instance;
    echo $instance['cst_twitter_screen_name']; //the variable i'm trying to access
    die();
}

public function widget( $args, $instance ) {
    //the widget instance
}

public function form( $instance ) {

    //the form
}

public function update( $new_instance, $old_instance ) {

    $instance = $old_instance;
    $instance['cst_twitter_screen_name'] = $new_instance['cst_twitter_screen_name'];

    return $instance;

}
5

You can get widget options using following code

$current_widget_options = $this->get_settings();

This will return array like array(instance number => settings). Instance number refers to the $number of widget.

Example: If your widget instance number is 2 then your required options will be at $current_widget_options[2]

Alternative:

As get_settings() is deprecated, you can use get_option. Check following example:

  $widget_options_all = get_option($this->option_name);
  $options = $widget_options_all[ $this->number ];
  • with get_settings() being deprecated, is it still acceptable to use it with plugins / widgets? get_options() is the alternative, but that doesn't return the value. – stoopkid1 Jul 13 '14 at 6:16
  • Check alternative in the above answer. :-) – Nilambar Jul 13 '14 at 6:28
  • I get an "undefined property" error with the Alternative, but I'll work that out somehow. Marked as correct answer =) – stoopkid1 Jul 13 '14 at 6:34
  • @stoopkid1 have solution on it? I have similar problem get_settings(); work fine for one plugin, but when I use two this same plugins...that's not work. stackoverflow.com/questions/42354968/… – mattkrupnik Feb 21 '17 at 11:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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