我试图从我在小部件中编写的自定义函数访问$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;
}
最合适的回答,由SO网友:Nilambar Sharma 整理而成
您可以使用以下代码获取小部件选项
$current_widget_options = $this->get_settings();
这将返回如下数组
array(instance number => settings)
. 实例编号是指
$number
小部件的。
示例:如果您的小部件实例号为2
那么您所需的选项将位于$current_widget_options[2]
Alternative:
像
get_settings()
已弃用,您可以使用
get_option
. 检查以下示例:
$widget_options_all = get_option($this->option_name);
$options = $widget_options_all[ $this->number ];