0

I'm Trying to scheduling wp_cron job in my website to send email everyday without opening my website but this is not happening. This work when user come to the website or reload a page.

Here is my code to scheduling cron job

// WP_CRON Scheduling

function my_custom_cron_schedule( $schedules ) {
    $schedules['every_one_minute'] = array(
        'interval' => 60, // Every 1 Minute
        'display'  => __( 'Every 1 Minute' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'my_custom_cron_schedule' );



//Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'my_cron_function_hook' ) ) {
    wp_schedule_event( current_time('timestamp'), 'every_one_minute', 'my_cron_function_hook' );
}

///Hook into that action that'll fire every One Minute
 add_action( 'my_cron_function_hook', 'my_cron_function' );

//create your function, that runs on cron
function my_cron_function() {
    $crtime = date('F-j-Y h:i:s');
    wp_mail('abc@example.com','Cron Job Test', "$crtime");
}
0

Wordpress Cron Jobs are not "real" Cronjobs, instead they relie on somebody visiting the site, then looking if it's time to do scheduled jobs.

1.: Someone visits the website

2.: Wordpress calls the file wp-cron.php

3.: wp-cron.php looks into the database if there are scheduled jobs that are due at this time.

4.: wp-cron.php does all of the scheduled jobs.


If you want to make sure that your cronjob is executed on time, you need to do some more steps:

1.: Schedule your cronjob. You did that already.

2.: disable the integrated Wordpress-Cron. Edit your wp-config.php and insert define('DISABLE_WP_CRON', true); below the line define('DB_COLLATE','');

3.: Create a "real" cronjob on your server, set to run every so often (5 Minutes, 15 Minutes, 1 Minute, something like that). I don't know if and how you can create a cronjob on your hosting, that's something you got to ask your hosting company. Make the target of your cronjob yourdomain.com/wp-cron.php

4.: Success! Your cron should work now as intended!

Happy Coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.