When you use *nix cron to run a PHP file like that it won’t have WordPress loaded. You can load it manually, but a better method is to use WordPress’ own cron API.
Schedule the event in your functions.php
:
if ( ! wp_next_scheduled( 'expire_posts' ) ) {
wp_schedule_event( time(), 'hourly', 'expire_posts' );
}
I’ve used hourly
, the other available defaults are daily
& twicedaily
(more on scheduling).
Now let’s hook up your expire_posts
function to our newly created expire_posts
event:
add_action( 'expire_posts', 'expire_posts' );
Tada!
NB: WordPress cron relies on a request (i.e. a user or bot visiting the site) at least as often as your schedule to run smoothly. If your site is quiet we can use *nix cron to trigger the WordPress cron API every 15 minutes and let WordPress handle its own internal events.
First, disable the default request-based cron behaviour in wp-config.php
:
define( 'DISABLE_WP_CRON', true );
Now set up a *nix cron to trigger WordPress’ cron:
/15 * * * wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron