Send specific users an email when posts are published

Question

I’ve got the following code, which is supposed to run when a new post is published for the first time, check if a custom field ‘specific_users’ has data (this uses Advanced Custom Fields), and if so, send an email to each of the selected users.

/**
 * Send users a notification of new grower posts 
 */
function notify_growers($post) {
// Only notify for grower posts
if ( $post->post_type != 'grower_posts' ) return;

$post_id = $post->ID;

// ...run code once
if ( !get_post_meta( $post_id, 'emailsent', $single = true ) ) {

    $specific_users = get_field('specific_users',$post_id);
    if(isset($specific_users) && is_array($specific_users)) {
        foreach($specific_users as $specific_user) {

            $to = $specific_user['user_email'];
            $subject = 'Grower News: ' . get_the_title($post_id);

            $message = '';
            $message .= '<p>' . get_the_excerpt($post_id) . '…</p>';
            $message .= '<p><a href="' . get_permalink($post_id) . '"><strong>Continue Reading &raquo;</strong></a></p>';

            wp_mail($to, $subject, $message );

        }
        unset($specific_user);
        //print("<pre>User IDs = ".print_r($user_ids,true)."</pre>");
    } else { return; }

    // Make sure this doesn't run again
    update_post_meta( $post_id, 'emailsent', true );
}

}
add_action( 'draft_to_publish', 'notify_growers' );
add_action( 'new_to_publish', 'notify_growers' );

It’s not sending any emails, and I’m not sure how to go about debugging it.

Side question, is sending the email in the foreach loop the best way to do it? Or should I do it all at once with BCCs somehow?

Thanks,
Angus

0
, Angus Russell 8 years 2013-05-21T22:05:17-05:00 0 Answers 78 views 0

Leave an answer

Browse
Browse