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;

}

1
1

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

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *