在 WordPress 中每天运行一段代码

use*_*756 2 wordpress user-registration

我正在使用 WordPress 注册插件。我陷入了用户过期的困境。实际上我想在会员注册一年后使会员过期。我想在到期前 1 个月通过电子邮件通知他们。我正在使用 add_action('init','my function name') 来检查有多少用户将在一个月后过期并发送邮件。bt 每次用户访问该网站时都会运行此操作挂钩,这将使我的网站每次用户访问时加载速度太慢。所以我想要一些能让这段代码每天运行一次的东西。例如,当第一个用户访问该网站时,该代码将运行,并且在剩余的一天内,无论有多少用户访问该网站,该代码都不会被调用。

lui*_*s90 8

Wordpress 有一个内置函数/API,可以完全执行您想要的操作 - 每天/每小时/您指定的任何时间间隔执行某些操作。

http://codex.wordpress.org/Function_Reference/wp_schedule_event

无耻地摘自上面的页面

add_action( 'wp', 'prefix_setup_schedule' );
/**
 * On an early action hook, check if the hook is scheduled - if not, schedule it.
 */
function prefix_setup_schedule() {
    if ( ! wp_next_scheduled( 'prefix_daily_event' ) ) {
        wp_schedule_event( time(), 'daily', 'prefix_daily_event');
    }
}


add_action( 'prefix_daily_event', 'prefix_do_this_daily' );
/**
 * On the scheduled action hook, run a function.
 */
function prefix_do_this_daily() {
    // check every user and see if their account is expiring, if yes, send your email.
}
Run Code Online (Sandbox Code Playgroud)

prefix_大概是为了确保不会与其他插件发生冲突,所以我建议你将其更改为独特的东西。

如果您想了解更多信息,请参阅http://wp.tutsplus.com/articles/insights-into-wp-cron-an-introduction-to-scheduling-tasks-in-wordpress/ 。

  • 谢谢朋友,这正是我正在寻找的东西。再次感谢您的快速回复。 (2认同)