Luca
Luca

Reputation: 299

Send mail after user submit his post in wordpress


In my website users can submit posts through a normal form.
My saved PHP variables are:

$usersarray = store the mail of the user
$postId = store the ID of the submitted post

The post submitted enter automatically in "Draft".
I would like to automatically send a mail when his post becomes "Published", how can I do it?

Of course this have to work with different users and different posts submitted, not only the last one. (each user have his post submitted)

Thanks in advice.

Upvotes: 0

Views: 1059

Answers (1)

Masivuye Cokile
Masivuye Cokile

Reputation: 4772

use the publish_post hook which is an action triggered whenever a post is updated and its new status is "publish".

To send an email via wp_mail() to the post author when their article is published.

function post_published_notification( $ID, $post ) {
    $author = $post->post_author; /* Post author ID. */
    $name = get_the_author_meta( 'display_name', $author );
    $email = get_the_author_meta( 'user_email', $author );
    $title = $post->post_title;
    $permalink = get_permalink( $ID );
    $edit = get_edit_post_link( $ID, '' );
    $to[] = sprintf( '%s <%s>', $name, $email );
    $subject = sprintf( 'Published: %s', $title );
    $message = sprintf ('Congratulations, %s! Your article “%s” has been published.' . "\n\n", $name, $title );
    $message .= sprintf( 'View: %s', $permalink );
    $headers[] = '';
    wp_mail( $to, $subject, $message, $headers );
}
add_action( 'publish_post', 'post_published_notification', 10, 2 );

Edit:

As @Stender have suggested in the comments below.

You could also use

draft_to_publish hook which will work perfect for what you require.

Upvotes: 6

Related Questions