I have a Cron Job to send email, it sends them but the recipients are hard coded. I also have a CPT for Clients, each post has an email meta, this CPT (clients) also has a renewal date. What I need is an scheduled task that sends an email to the clients soon to be renewed.
This is how I coded the task:
function soon_to_renew() {
$query = new WP_Query(array('post_type' => 'client'));
$clients = $query->get_posts();
foreach($clients as $client) {
$dateToRenew = get_post_meta( get_the_ID(), 'client_renewal_date' );
$dateToRemindClient1 = $dateToRenew - 25;
$dateToday = date(z);
if( $dateToday == $dateToRemindClient1 ) {
$recepients = get_post_meta( get_the_ID(), 'client_email' );
$subject = 'Tu cuenta está próxima a renovarse';
$message = 'En los próximos días tu contrato vencerá, no olvides realizar el pago para renovar tu cuenta.';
wp_mail($recepients, $subject, $message);
}
}
}
Andrea P answers:
hello!
if your function is already correct, you can easily set a cron job which calls that function on a recurring time.
add_action('init', 'schedule_renewals_check');
function schedule_renewals_check(){
if ( !wp_next_scheduled('soon_to_renew') ){
wp_schedule_event(time(), 'daily', 'soon_to_renew');
}
}
this will set up a cron job which will trigger the function soon_to_renew() on a daily basis. you can change daily and put hourly or whatever else:
https://codex.wordpress.org/Function_Reference/wp_schedule_event
Alvaro Rosado comments:
Hi Andrea, yep i had the cron scheduled task already set up, i just needed for a loop to find all the soon to renew clients. Just did it though, i was missing the global $post
this is what i ended with:
function soon_to_renew() {
global $post;
$args = array(
'post_type' => 'client',
'posts_per_page' => -1
);
$clients = get_posts( $args );
foreach( $clients as $post ) : setup_postdata($post);
$dateToRenew = get_post_meta( get_the_ID(), 'client_renewal_date' );
$dateToRemindClient1 = $dateToRenew - 25;
$dateToday = date(z);
if( $dateToday == $dateToRemindClient1 ) {
$recepients = get_post_meta( get_the_ID(), 'client_email' );
$subject = 'Tu cuenta está próxima a renovarse';
$message = 'En los próximos días tu contrato vencerá, no olvides realizar el pago para renovar tu cuenta.';
wp_mail($recepients, $subject, $message);
}
endforeach;
}
add_action ('soon_to_renew', 'daily_task');
Andrea P comments:
so you didn't need my code to setup the cron job?
by the way, I am not sure that you actually need the global $post. while you surely need the setup_postdata.
I would also add a wp_reset_postdata() at the end of the function, after the endforeach.
Alvaro Rosado comments:
Nope, i had the cron job already set up, the foreach was returning empty, when i added the global $post started to work.