Skip to content

Instantly share code, notes, and snippets.

@DavidLemayian
Last active April 9, 2016 02:35
Show Gist options
  • Save DavidLemayian/6087222 to your computer and use it in GitHub Desktop.
Save DavidLemayian/6087222 to your computer and use it in GitHub Desktop.
Automatically notify users of a new post. Simply add this piece of code to your functions.php file to have it working. FEATURES: - Automatically sends an email to notify registered users of a new post. - Allows for rich text formatting through HTML. - A brief of the content to expect. - Links back to the exact post and blog. - Sends email only o…
/*
EMAIL NOTIFICATION OF NEW POST
Add this to the functions.php file.
*/
function email_members($post_ID) {
global $wpdb;
// Check if notification for this post has already been sent
$already_sent = get_post_meta($post_id, 'mail_notification_once', true);
if(!$already_sent) {
// Get the registered users' emails.
$usersarray = $wpdb->get_col("SELECT user_email FROM $wpdb->users;");
$users = implode(",", $usersarray);
// Get the blog's name, url and email address
$blog_title = get_bloginfo('name');
$blog_url = get_bloginfo('url');
$blog_email = get_bloginfo('admin_email');
// Get the post's data and url.
$post_data = get_post($post_ID);
$permalink = get_permalink($post_ID);
//Get Author Details
$author_id = $post_data->post_author;
$author_name = get_the_author_meta( 'user_nicename' , $author_id );
// Get the post content
$post_short = substr($post_data->post_content, 0, 500);
// Set the subject and body
$subject = $blog_title." | New Post - ".$post_data->post_title;
$body = '
<!DOCTYPE html>
<html lang="en">
<head>
<title>'.$blog_title.' | '.$post_data->post_title.'</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
</head>
<body>
<div class = "container">
<h1>'.$post_data->post_title.'</h1>
<p>
<small>Author: '.$author_name.'</small> <br/>
<small>Date: '.$post_data->post_date.'</small>
</p>
<p>'.$post_short.'...</p>
<p><a href="'.$permalink.'" class="btn btn-primary">Read More</a></p>
<br/>
<p class="text-center">Proudly Published on <a href="'.$blog_url.'">'.$blog_title.'</a></p>
<br />
</div>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'From: '.$blog_title.' <'.$blog_email.'>' . "\r\n";
// Send the email(s)
mail($users, $subject, $body, $headers);
return $post_ID;
add_post_meta($post_id, 'mail_notification_once', 1, true);
}
}
// Add action hooks when published either from draft or from new
add_action('draft_to_publish', 'email_members');
add_action('new_to_publish', 'email_members');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment