Получить экземпляр виджета внутри виджета


Я пытаюсь получить доступ к переменной $instance из пользовательской функции, которую я написал в своем виджете, но я продолжаю получать ошибку "переменная не определена".

Как я могу воссоздать переменную $instance?

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;

}
 6
Author: stoopkid1, 2014-07-13

1 answers

Вы можете получить параметры виджета, используя следующий код

$current_widget_options = $this->get_settings();

Это вернет массив, подобный array(instance number => settings). Номер экземпляра относится к $number виджета.

Пример: Если ваш номер экземпляра виджета 2, то необходимые параметры будут на $current_widget_options[2]

Альтернатива:

Поскольку get_settings() устарел, вы можете использовать get_option. Проверьте следующий пример:

  $widget_options_all = get_option($this->option_name);
  $options = $widget_options_all[ $this->number ];
 5
Author: Nilambar Sharma, 2014-07-13 06:24:23