I am trying to wrap my head around wp cron jobs and have been playing around with the following snippet of code, which is supposed to send an email to the specified email address once an hour, provided of course that a visitor has visited the site and triggered the job (wp cron jobs aren't apparently real chron jobs, I've come to understand).Now, the job works in that an email gets sent to the email address, but there are two problems:The email gets sent multiple times per chron jobCron jobs seem to be triggered on every page load even though it's not supposed to run more than once an hourHere's the code (retrived from wp_schedule_event not firing):if ( ! wp_next_scheduled( 'prefix_hourly_event' ) ) { wp_schedule_event( time(), 'hourly', 'prefixhourlyevent');}add_action( 'prefixhourlyevent', 'prefix_do_this_hourly' );function prefix_do_this_hourly() { wp_mail('myemail@gmail.com','Cron is working', 'Cron is working: ','','');}Would anybody be able to give me an idea of why not just one email gets sent every hour? //Mega WP Noob 解决方案 You're checking if an event is scheduled and when it's not found you're registering it under a different name. The mismatch is what's causing it to run on every page load.Change this:if ( ! wp_next_scheduled( 'prefix_hourly_event' ) ) {To this:if ( ! wp_next_scheduled( 'prefixhourlyevent' ) ) {I'd also look at whether you can check the schedule once rather than on each page load. If you were writing a plugin for example you could fire it on the plugin activation hook.Further reading: https://codex.wordpress.org/Function_Reference/wp_schedule_event 这篇关于WP Cron作业在每次加载页面时运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-23 02:02
查看更多