To run something every 24 hours, you can use the WP Cron system. However, keep in mind:
wp-cron
is ran/checked after every page load. If nobody visits your site for 2 days no cron jobs can run, it needs visitors to get an opportunity to run- Because it needs visitors to the site for the chance to check, it won’t run it at exactly the right time. If it’s due at 12:00, but nobody visits until 13:01, then it won’t have the opportunity until 13:01
- Your code relies on
$post_id = $_GET['post'];
which will not be possible in a cron job, cron jobs are a separate web request, so there are no POST or GET values. You will need to store this value in an option somewhere so it knows what the post ID will be
Now we have the caveats out the way, this is how a daily WP Cron schedule should be set up:
if ( ! wp_next_scheduled( 'your_hook' ) ) { // if it hasn't been scheduled
wp_schedule_event( time(), 'daily', 'your_hook' ); // schedule it
}
....
add_action( 'your_hook', 'your_function' );
I’d recommend doing this on the init
hook. To make it happen after a specific time each day, modify the time passed to wp_schedule_event
to the next time it should run. E.g. if it’s 7pm monday the 5th, and we want it to run at 5pm every day, give it 5pm Monday the 6th. Doing that is a PHP problem not a WP problem though, and luckily stack overflow has a great answer here.
Making It Run At Exact Times Regardless of Visitors
If you have the good fortune of being able to set a system level cron job, you can remove the need for visitors to your site for WP Cron to work:
https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/
- disable WP Cron in
wp-config.php
- Manually run the cron event in WP from a system cron job ( crontab? )
- by either pinging the URL directly
- or using WP CLI to execute the cron job
- if you’re feeling adventurous and know your dev ops/server admin, setup the cavalcade service to run wp cron tasks
- Note that if you’re on a multisite, you will need to do this for every blog, WP Cron won’t run for every single site if you don’t explicitly run it for each one
Further Reading
For further reading, the official docs plugin handbook has a section on cron jobs: