Schedule query once a week
-
Good morning everyone.
As the title says I’m trying to find a way to schedule a wordpress query to run every week.
In my site (currently in local environment) I have a section with a group of custom posts, obtained randomly from different categories, used to show the suggested posts of the week.
I’d like to find a way to get new post every week without having to set up the post manually.Looking around I’ve found the functionality
wp_cron
that seems to be the right thing to use, since I can’t set up a cron job directly on the server.Trying to understand how it works I’ve created a sort of try-out function in my functions.php
function custom_time_cron( $schedules ) { $schedules['every_week'] = array( 'interval' => 604800, //604800 seconds in 1 week 'display' => esc_html__( 'Every Week', 'textdomain' ) ); return $schedules; } add_filter( 'cron_schedules', 'custom_time_cron' ); add_action( 'my_cron_hook', 'my_cron_function' ); if (!function_exists('mytheme_my_activation')) { function mytheme_my_activation() { if (!wp_next_scheduled('my_cron_hook')) { wp_schedule_event( time(), 'every_week', 'my_cron_hook' ); } } } add_action('wp', 'mytheme_my_activation'); if (!function_exists('my_cron_function')) { function my_cron_function() { echo time(); } }
I then call the hook in my page with the following
do_action('my_cron_hook');
With this function I was expecting to get the same timestamp everytime I refresh the page until the next week when it should be updated.
Since this is my first time working with wp_cron it’s possibile that I’ve missed something or that wp_cron is not the right thing to use.
So I’d like to know if there are errors in the structure of my code or if there are better ways to achieve this result.
Any help will be really appreciated!
- The topic ‘Schedule query once a week’ is closed to new replies.