Automatically Sent Email to all Your Members when New Posts added to wordpress

Many of the times, we all depends upon the plugins to do most of our work. But sometimes, its better to code it on your own so that you can play with the code and can make any changes as per your requirement. This can be possible only if you are clear with the code and you did that code yourself. So in today’s tutorial, we will learn about “how to Automatically Sent Email to all Your Members when New Posts added to wordpress”.

You don’t need to work so much to do this task. We are providing you everything. Just copy and paste the following code into your function.php file:

<?php
function email_members($post_ID)  {
	global $wpdb;
	$usersarray = $wpdb->get_results("SELECT user_email FROM $wpdb->users;");
	$wp_user_search = new WP_User_Query( array( 'fields' => array('user_email') ) );
	$usersarray = $wp_user_search->get_results();
	$arrUsers = array ();
	for ($arr = $usersarray, $mU = count ($arr), $iU = 0; $iU < $mU; $iU++) {
		$arrUsers[] = $arr[$iU]->user_email;
  } // for
  $users = implode(",", $arrUsers); 
  $siteurl= get_bloginfo("siteurl");
  $siteurl_link ='<a target="_blank" href="'.$siteurl.'">'.$siteurl.'</a>'; 
  $subject = 'New post notification :' . get_bloginfo("name"); 
  $post_link ='<a style="font-size: 20px;text-transform: capitalize;" target="_blank" href="'.get_permalink($post_ID).'">'.get_the_title($post_ID).'</a>';
  $message = '<html><body>';
  $message .= 'A new post<b> '.$post_link.' </b>has been published on<b> '.$siteurl_link.' </b>' ; 
  $headers = 'From: techTutorialsOnline <info@techTutorialsOnline.com>';
  $headers .= "MIME-Version: 1.0rn";
  $headers .= "Content-Type: text/html; charset=ISO-8859-1rn";
  wp_mail($users,$subject,$message,$headers);
  return $post_ID;
}
add_action('publish_post', 'email_members');

That’s all you need. Now every time when you publish a new post then the email will be sent to the members of your website.