0

I would like to write a Wordpress plugin that sends one email every day for 7 days for newly registered users but I'm not sure how to start.

My plan would be:

  • hook the register function to send the first email after the user registers, send some users details to a custom table(for now the colums are just the user id and a counter with the number of emails sent)

  • use a cron script that runs every 24h that would get data from that table and, if needed, send the emails and increment that counter

Is there a better way to approach this?

2

There is no need for a custom table here - you can use the user metadata table and API.

Then create a WP-Cron job to run every 24 hours (or more frequently if you're paranoid). On the callback query users who've registered in the last 7 days using something like:

/*
 * Get all users registered after $start and before $end (dates in yyyy-mm-dd format)
 * Based on my answer to this question: http://wordpress.stackexchange.com/questions/51485/how-can-i-query-all-users-who-registered-today/51492#51492
 * @param (string) $start - start date in yyyy-mm-dd format
 * @param (string) $end - end date in yyyy-mm-dd format
 */
function wpse51485_get_users_registered($start='', $end='' ){
    global $wpdb;

    if( empty($start) )
        $date = date('Y-m-d');

    if ( empty($end) )
        $end = $start;

    //Should probably validate input and throw up error. In any case, the following ensures the query is safe.

    $start_dt = new DateTime($start. ' 00:00:00');
    $s = $start_dt->format('Y-m-d H:i:s');

    $end_dt = new DateTime($end.' 23:59:59');
    $e = $end_dt->format('Y-m-d H:i:s');

    $sql = $wpdb->prepare("SELECT wp_users.* FROM wp_users WHERE 1=1 AND CAST(user_registered AS DATE) BETWEEN %s AND %s ORDER BY user_login ASC",$s,$e);

    $users = $wpdb->get_results($sql);

    return $users;
 }

and finally loop through them, and send an email if required (using and updating the user's meta appropriately).

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.