Issue
Question about PHP, wordpress and CRONE. I can't get global variable changed by CRON procedure in function, called by widget.
$container
register_activation_hook(__FILE__, 'activate_my_plugin');
function activate_my_plugin() {
wp_clear_scheduled_hook('update_container');
wp_schedule_event( time(), 'hourly', 'update_container');
}
add_action('update_container', 'update_container');
function update_container() {
global $container;
// updating container
}
function use_container() {
global $container;
// !And here we have undefined $container
}
class acw_widget extends WP_Widget{
// ...
public function widget( $args, $instance )
{
use_container();
}
}
I'm trying to cache the requests to DB on WP site. So, I decided to use CRON to schedule the requests and store the results in some global container. It's supposed that widget will fetch data from container for its purposes, but I faced the problem that looks like as 'undefined container'.
So, I activate plugin, wp-cron.php shows, that container was updated (at 'update_container'), but fetching the container in 'use_container' shows, that $container is undefined and was not updated.
Please, could you explain, why this happens? How can I trace the correct sequence of initializing/updating the global container?
The code is simplified version of the real one. Maybe it's awkward, but I'm new in PHP and wordpress, so this is the way of solution I'v found.
Thanks
Solution
You can't use any variable (inc global
) as data "container". Because PHP has no state, each of php script runs going "from scratch".
So, when your CRON
script runs - it's update global $container
only for this current run. Then, when you run your widget
functionality - it is another "run" and you will find out that $container
is not defined.
What you need, instead of just using variable, is to store your data inside database (by the same CRON
script for example). Then, each time you need that data - just get it from database.
Hope that clarify something to you.
Answered By - krylov123