Good morning everyone. As the title say I'm trying to find a way to run a wordpress query every week to update a section in my site with the suggested posts of the week.
Looking around I've found the wp_cron
feature, and it seems like the thing I'm looking for since I can't set up a cron job on the server.
The problem is that I wasn't able to make it work.
I've created this try-function in my functions.php
add_action( 'cron_hook', 'cron_exec' );
if( !wp_next_scheduled( 'cron_hook' ) ) {
wp_schedule_event( time(), 'daily', 'cron_hook' );
}
function cron_exec() {
echo time();
}
And i call the action in my post page with the following code:
do_action('cron_hook');
This is my first attempt at wp_cron so maybe I missed something but I was expecting to get the same time() everytime I refresh the page since the function should be fired once a day, but I ended up having the current timestamp on every refresh.
I'd like to know if I'm using correctly the wp_cron function and if it's the right thing to use in this case or there are bettere methods to achieve this result.
Thank you for the help and have a nice day.
To execute cron every week you'll need something like this:
The first function creates a new schedule - because you only have
houly
,daily
andtwicedaily
as a reccurance.Then you set up your scheduler. You check if there is a scheduled event with
!wp_next_scheduled
, and if it's not, you schedule the eventIf you've already initialized a cron with a certain name, for it to get rescheduled you'll need to wp_clear_scheduled_hook.
Hope this helps :)