There shouldn’t be limitations if used correctly, wp_cron events are piggy backed onto normal WP requests, so the default environment should be initiated as it would be for that original request. How are you invoking your wp_cron? If you use wp_schedule_event() to fire an action hook whose callback does a WP_Query, it should all work.
I’ve set up wp_schdedule_event and have confirmed that the cron job is scheduled. However, the lowest interval I have found to use is daily. So to test it I am hitting the wp-cron.php file and calling the function in the top of the plugin file where I am writing this functionality.
Is there a better way to test the function that would put it in the proper environment?
Thanks for the help!
“The loop” is not set up in WP_CRON, though it might be possible to set it up manually. You should probably consider using direct queries to the database to obtain the data you require.
I don’t really need the loop, it was just the easiest way I could think of to accomplish what I was trying to do. Would a get_posts call work? I really just need an array of the posts I need that I am able to loop over.
Thanks!
get_posts() is a wrapper for WP_Query. Either will work. If you don’t need to run your process as often as daily, keep track of when it last ran and when the cron event fires, see how many days it has been. If it has not been enough days, just exit the process. Yes, this process takes a little extra time, but it’s better than needlessly running the entire thing more than necessary.
If you are willing to stipulate that the scheduling works and WP will fire the action you scheduled at the correct interval, to test just your code, fire your scheduled action yourself with a do_action() call from a normal WP process, such as a template, Ajax request, or request sent through /wp-admin/admin-post.php. Loading only wp-cron.php does not correctly replicate the environment as it actually runs.
I’m fine to use the daily timing. It was just a matter of figuring out how to test the functionality. Calling my function in a template file works just fine to test things out. And the WP_Query stuff is working normally when called in that context.
Thanks for the help!