I’m trying to schedule a pseudo cron job to send an email after a set amount of time utilizing a WordPress plugin.

So far, I’ve been able to make this code run when I hard code the email address and message into the email_about_coupon() function. However, when I try to send the arguments to the function, the email is never sent.

By using the Cron GUI plugin, I’m able to see that the cron job is registered even with the arguments. I believe that I’m doing something incorrectly that does not allow the arguments to be used properly within the function at the time that it is run.

Here’s what I have:

function schedule_email_cron($post_id)
{
    // Get the UNIX 30 days from now time
    $thirty_days = time() + 60; // (30 * 24 * 60 * 60)
    $post = get_post($post_id);
    $email = get_the_author_meta('user_email', $post->post_author);
    $args = array('email' => $email, 'title' => $post->post_title);
    wp_schedule_single_event($thirty_days, 'email_about_coupon_action', $args); 
}

add_action('save_post', 'schedule_email_cron', 1, 1);

add_action('email_about_coupon_action', 'email_about_coupon', 1, 1);

function email_about_coupon($args)
{
    // Email text
    $text = "<html><body><p>Your coupon titled, ".$args['title']." is expiring soon. Please visit <a href=\"\">".get_bloginfo('siteurl')."/registered/</a> ".get_bloginfo('siteurl')."/registered/ to renew your coupon.</p></body></html>";

    // Email headers
    $headers = array(
        'From: '.get_bloginfo('name').' <'.get_bloginfo('admin_email').'>',
        "Content-Type: text/html"
    );
    $h = implode("\r\n",$headers) . "\r\n";

    // Send email
    wp_mail($args['email'], 'Renew Your Coupon Now!', $text, $h);
}

As always, thanks so much for your help!

2 s
2

I think you have mismatch in how you pass arguments and how you expect it to work. You pass array of arguments to schedule and expect your hooked function to receive identical array of arguments. This is not the case.

Cron events are processed by do_action_ref_array(), which in turn passes arguments via call_user_func_array().

So your hooked function does not receive array of arguments, it receives multiple arguments – one for each element in your array.

So you need to either wrap array of arguments in array one more time or modify your function to process multiple arguments. Note that for letter you will also need to modify your add_action() call so that required number of arguments is passed instead of just one.

Leave a Reply

Your email address will not be published. Required fields are marked *