1
votes

I am trying to create a testimonial form and listing page in Wordpress and I'm having problems with sending an email to the testimonial author, notifying him that his post was published.

After the form is validated and processed it automatically creates a pending post with wp_insert_post() and the form details are stored in text inputs generated from the Advanced Custom Fields plugin. When I click the publish button it should send a notification email to the author. Here's the function I've wrote:

function publish_post_notification($post_id){

  $author = get_field('author_email', $post_id); // get author email from custom fields

  if(isset($author)){
    require_once('testimoniale/mail-config.php'); // PHPMailer config
    $mail->addAddress($author);   // Add a recipient
    $mail->Subject = 'Your testimonial has been published !';

    ob_start();
    include('testimoniale/mail_template/notification-template.php');
    $mail->Body = ob_get_contents();

    $mail->AltBody = 'Your testimonial has been published !'; // Alternative text for non-html mail clients

    if(!$mail->send()) {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
    ob_end_clean();
}  

add_action('publish_post','publish_post_notification',10,1);

The problem is when I publish the post for the first time, it doesn't send an email but it does if I, for example, change the post status afterwards to Pending and the publish it again or if I update the post.

I've tried using the save_post hook, but it fires when the post is initially created through wp_insert_post() as well, and for some reason transition_post_status, pending_to_publish and post_updated didn't work for me either.

Any suggestions ?

Thanks in advance

1
use the save post hook and check the post status within the function.You can set post meta to prevent further emails.David
Could you give me an example please? How would I go about checking whether or not the post is being created so the hook doesn't fire then ?Cosmin Achim
try it yourself first, you can use get_post to pull the post and then use update_post_meta() to save custom data.David
Thanks for your suggestions. I eventually found out what was wrong and posted an answer below.Cosmin Achim

1 Answers

2
votes

I found out what was wrong with my code: the get_field() function from Advanced Custom Fields didn't return the author field value on the first post publish, hence the if(isset($author)) condition was returning false.

I've changed $author = get_field('author_email', $post_id); to $author = get_post_meta($post_id, 'author_email', true); and now it works