且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

每周运行一次wordpress查询

更新时间:2022-12-26 17:35:44

To execute cron every week you'll need something like this:

function custom_time_cron( $schedules ) {

    $schedules['every_week'] = array(
            'interval'  => 604800, //604800 seconds in 1 week
            'display'   => esc_html__( 'Every Week', 'textdomain' )
    );

    return $schedules;
}
add_filter( 'cron_schedules', 'custom_time_cron' );

add_action( 'my_cron_hook', 'my_cron_function' );

if (!function_exists('mytheme_my_activation')) {
    function mytheme_my_activation() {
        if (!wp_next_scheduled('my_cron_hook')) {
            wp_schedule_event( time(), 'every_week', 'my_cron_hook' );
        }
    }
}

add_action('wp', 'mytheme_my_activation');

if (!function_exists('my_cron_function')) {
    function my_cron_function() {
        echo time();
    }
}

The first function creates a new schedule - because you only have houly, daily and twicedaily as a reccurance.

Then you set up your scheduler. You check if there is a scheduled event with !wp_next_scheduled, and if it's not, you schedule the event

wp_schedule_event( time(), 'every_week', 'my_cron_hook' );

If you've already initialized a cron with a certain name, for it to get rescheduled you'll need to wp_clear_scheduled_hook.

Hope this helps :)