Improving websites in Lancaster County, Pennsylvania.
Need help? Call or email Corey →
💡 Code that works in a plugin might not behave the same in a scheduled wp-cron job.
Things That Don’t Always Work in WordPress Cron Jobs
get_posts()calls that return posts with unpublished statuses
$wpdbqueries to retrieve posts or force admin
- Other functions or codes that call
Why do wp-cron jobs behave differently?
WordPress cron jobs are triggered by any visitor to your site on or after the scheduled time. A logged-out visitor could be running your WordPress cron job.
Any code that uses
current_user_can() to restrict permissions can behave differently during wp-cron, including
Pick one, both are not needed.
1. Test Your Code as a Logged-Out Visitor
Testing wp-cron job code with a tool that runs tasks on demand (like Advanced Cron Manager) will fool you into believing the code will always run as an Administrator user. Use a short interval during development so it’s easier to trigger jobs as a logged-out visitor.
2. Briefly Force Adminstrator
wp_set_current_user() to explicitly user an Administrator account at the beginning of your job’s code, and restore the original user ID even if zero to avoid leaking Administrator privileges.
$user_id = get_current_user_id(); //could be 0 wp_set_current_user( 1 ); //1 is the user ID of an Administrator //do the stuff that needs to run as an admin $drafts = get_posts( array( 'post_status' => 'draft', //drafts aren't accessible to logged-out users ) ); //don't leak Administrator privileges, restore the previous user even if 0 wp_set_current_user( $user_id );