Save variable state in widget

I’m creating a worpdress widget. It shows random number. New number generates every n minutes (for example), while previous number must display in widget.
The trouble is: old number doesnt save and show, its just nullify. Widget shows number only when in if statement.

I tried to use static variable but it doesnt help obviosly. How can i store and display old variable until new generation? Can i use update() from widget()?

Code example

class My_Widget extends WP_Widget{

static public $random;

// __constructor ///

public function widget($args, $instance){
$random_array = array(1,2,3,4,5,6,7,8,9,0);
$title = apply_filters( ‘widget_title’, $instance[ ‘title’ ] );
$update_timer = !empty($instance[‘update_interval’]) ? (int)$instance[‘update_interval’] : 10;
$def_timer = $instance[‘current_time’];

$random = My_Widget::$random;

$current_time = new DateTime(‘now’);

if((int)($current_time->diff($def_timer)->i ) % $update_timer === 0) {
My_Widget::$random = $random_array[array_rand($random_array)];
$random = My_Widget::$random;
echo $args[‘before_widget’] . $args[‘before_title’] . $title . $args[‘after_title’]; ?>
<p><?php echo $random ?></p>
<?php echo $args[‘after_widget’];
public function form($instance){


public function update( $new_instance, $old_instance ) {

Read more here:: Save variable state in widget

Leave a Reply

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