1. Skip to Navigation
  2. Skip to Content
our blog

WordPress: Send Notification E-mails On Publish

Updated: 4/29/2013

We recently developed a site for a client that allows visitors to submit their stories using a custom form. The stories then go into a queue to be reviewed for approval by an Administrator. One requirement was that these user’s be notified by email if their story was approved.

After not finding any plugins designed specifically to do this, I cooked up a little function that I thought I would share.

Note: this code assumes you already have the user’s email available as a custom field on the post.

First we need to create a function that loads the e-mail address from the published post’s ID and sends a message. Add the following code to your theme’s functions.php:

//send notification e-mail on story publish
function ik_send_email($post_id){
	//get e-mail address from post meta field
	$email_address = get_post_meta($post_id, '_ikcf_user_email', true);
 
	$subject = "Your Subject Here!";
	$body = "Thank you for your submission!  Your story has been approved!";
 
	//use this to set the From address of the e-mail
	$headers = 'From: From Address <[email protected]>' . "\r\n";
 
	if(wp_mail($email_address, $subject, $body, $headers)){
		//mail sent!
	} else {
		//failure!
	}
}

With that function in hand, we just need to add it to the ‘publish_post’ hook:

//send notification e-mail on post publish
add_action('publish_post','ik_send_email');

And that’s it! A straightforward solution to send notification e-mails on publish.

Update:
Per Matt’s comment, below, if you are trying to get a custom field on a post that hasn’t been saved yet, you’ll need to change the way in which you retrieve the field and collect it from the POST, instead.

Feel free to ask questions in the comments below.

12 Responses to WordPress: Send Notification E-mails On Publish

  1. Martin says:

    Hi Richard,
    would it be possible to get the email adress from a custom field which is filled by the author when he creates a new post?
    I would like so send 1 email on every post when the post is published. although, the email adress keeps changing…

    • Hey Martin -

      $email_address = get_post_meta($post_id, '_ikcf_user_email', true);

      Absolutely. In the code example, replace ‘_ikcf_user_email’ with the name of your custom field and it should have the desired effect.

      Let me know if that works or if you need any more help.

      Thanks!
      Richard

  2. Martin says:

    Hi Richard,

    sorry for the late response. Was a busy time. :-)

    Thanks for the input, but unfortunately it doesn’t work. Everything is just gerat, but I can’t pull the custom field ($email_adress). Have taken a look into the data base and the value is existing… :(

    Any idea?

  3. Philipp says:

    Hey Richard,

    this is exactly the solution i need, thank you very much! I am not quite sure where to add the second code snippet (the add_action part). Can i post it anywhere in the functions.php?

    And somehow i cant add a custum field using _ikcf_user_email but when i use ikcf_user_email is works well. Does this work when i modifiy the first snippet in line 4?

    Regards and thank you!
    Philipp

  4. Dave says:

    This was very helpful, but do you have any idea why it can’t pull the email address from the custom field if you use pending_to_publish instead of publish_post? We really only want it to send the notification on the first approval but not if future changes are made…

  5. Matt says:

    I am having an issue here as well. For the life of me I cannot understand why the email field does not return for me. I have a custom post type of “invoice”. Everything works with the email except extracting the email field from the post meta.

    $client_email = get_post_meta($post_id, ‘invoice_user_email’, true);

    I am a pretty advanced wordpress coder but this one has me stumped. Especially since we are calling the post meta by post id. Should be plain and simple.

    Any ideas?

    • Hey Matt -

      I just retested my code on my end, two ways, with success, on version 3.5.1.

      My first test, I saved the post as a draft from a limited user account and then published the post from the administrator account. The e-mail address was setup as a basic text custom field and I queried it as a single string (3rd argument of get_post_meta set to true.)

      My first test was successful.

      My second test I created the post as the administrator and went straight to publish – no intermediary draft status. The custom field was setup and queried the same way as the first test.

      My second test was successful.

      My thought:
      - Maybe you need to query your custom field differently. I’m not sure how you’ve set it up; here is what I’ve done, essentially (this isn’t the full code, its a snippet from a larger class):

      $fields = array();  
      $fields[] = array('name' => 'user_email', 'title' => 'User Email', 'description' => 'The User Email.', 'type' => 'text');
       
      foreach ($fields as $f)
      		{
      			$this->customFields[] = array
      			(
      				"name"			=> $f['name'],
      				"title"			=> $f['title'],
      				"description"	=> isset($f['description']) ? $f['description'] : '',
      				"type"			=> isset($f['type']) ? $f['type'] : "text",
      				"scope"			=>	array( 'post' ),
      				"capability"	=> "edit_posts"
      			);
      		}
       
      add_meta_box( 'my-custom-fields'.md5(serialize($this->customFields)), $this->customPostTypeSingular . ' Information', array( &$this, 'displayCustomFields' ), $this->customPostTypeName, 'normal', 'high' );

      Anyways, let me know if this is helpful at all or not.

      Thanks,
      Richard

      • Matt says:

        Thanks for the quick reply!
        Let me show you what I currently have and maybe you can see why it would not be working. To explain a bit further, I have created an invoice plugin with a custom post type of “invoice”. The mail function is part of this custom plugin.


        ID, 'invoice_user_email', true);
        $email_subject = "You have a new invoice";

        $client_name = get_post_meta($post->ID, 'invoice_user', true);
        $message = $client_name.';Your latest invoice is now available online.';

        wp_mail($client_email, $email_subject, $message);

        }
        ?>

        I have even tried inputting the post id manually and still the values are not returned for the post meta. I haven’t tried putting your method into use yet, but thought I would show you what I am trying to accomplish.

        • Matt says:

          sorry the code didnt come through right

          function invoice_publication_notification($post_id) {

          $post = get_post($post_id);
          $client_email = get_post_meta(462, 'invoice_user_email', true);
          $email_subject = "You have a new invoice";

          $client_name = get_post_meta(462, 'invoice_user', true);
          $message = $client_name.';Your latest invoice is now available online.';

          wp_mail($client_email, $email_subject, $message);

          }

          • Matt says:

            Ok I FINALLY got it working…..here was my issue in case anyone else has the problem. I was trying to call post meta that was not yet saved so what I did instead was pull data from the custom meta box…. $invoice_user = $_POST['invoice_user']; for example. Now it all works fine.
            Hope this helps.

  6. Kleidi says:

    Hello there,
    First of all i want to thank you for this function. I’m wondering how can i do it to send posts to some users depending on the category the post is published. Example:
    If the new post is published in category “Sport” the function gets the post and sends it to 2-3 email addresses that are manually putted in the function.
    If another post is published in category “Politics”, the function gets the post and sends it to other 2-3 addresses.
    I have up to 15 mail addresses that should receive the new published posts by mail.
    Thank you and hope that you will help me with a way to do it.

Leave a Reply

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


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>