Automatically updated server variable with Frontend output

Hi,
Sorry I searched so much but got no answer in the www. I need to do the following (simplified):

  1. Define a variable with init value (e.g. 500)
  2. Make a calculation each day and alter the variable (eg. add 100)
  3. Display that variable in the frontend in elementor

It seems so easy, but in detail I struggle a lot. My idea was to a define a global variable in functions.php, add a cron job with calls a function each day in functions.php. Then add a shortcode to a function that returns the global variable and insert that shortcode into elementor. All works but not the alter of the variable. I miss something fundamental I think, as I am a newbie…

global $clients;
$clients = 500;

function cron_update() {
global $clients;
$clients += 100;
}
function get_clients() {
global $clients;
return $clients;
}
add_shortcode(‘GETCLIENTS’, ‘get_clients’);

I always get 500 as a result. Also after several cron jobs. I think the functions.php is called on each pageload so the init of the var is overwritten each time. How can I avoid that?

I also tried:

if (!isset($clients)){
global $clients;
$clients = 500;
}

but it seems also that it does it on each reload. So how can I define real global variables which stays intact?

I tried with GLOBALS but also no success…

Thank you,
Chris

PHP code itself isn’t persistent; you’ll need to store the number (in a file or the database for example) if you want it to persist.

You might not need to though. If you just want to show a higher number every day, you can do it as follows:

// Your initial value
$start_number = 500;

// your increment
$increment_by = 100;

// The date on which your counter starts
$start_date = new DateTime('2021-02-18');

$time_since_start = $start_date->diff(new DateTime);

$current_value = 500 + $time_since_start->days * $increment_by;

$current_value will now be 500, plus 100 more for every day that passes after today.

hey thank you so much! You saved my day. Puhhh!
You are right with calculating the number based on the date but this was a simplified problem. At the end I need to do calculations based on the current number. So how can I store that in the database? Is there some sort of CONSTANTs table or so in Wordpress?

You want the options API.

Thank you skawid. Great support…

Sponsor our Newsletter | Privacy Policy | Terms of Service