If you’re managing a WordPress website where users submit posts through a frontend form, it’s common to keep these submissions as drafts for review before publishing. Once reviewed and approved, you may want to automatically send an email to the post author notifying them of the publication.

To achieve this, we can utilize the “transition_post_status” hook in WordPress. This hook allows us to perform actions when a post changes its status, in this case, from “draft” to “publish.”

Let’s break down the code:

add_action( 'transition_post_status', 'send_email_on_publish', 10, 3 );

/**
 * Sends an email when the post status changes from "draft" to "publish."
 *
 * @param string $new_status New post status.
 * @param string $old_status Previous post status.
 * @param object $post The WP_Post object.
 */
function send_email_on_publish( $new_status, $old_status, $post ) {

    // Check if the status transition is from "draft" to "publish" and the post type is "post."
    if ( $old_status === 'draft' && $new_status === 'publish' && $post->post_type === 'post' ) {

        $author_id = $post->post_author;
        $author_display_name = get_the_author_meta( 'display_name', $author_id );

        // If display name is empty, use the user login.
        if ( empty( $author_display_name ) ) {
            $author_display_name = get_the_author_meta( 'user_login', $author_id );
        }

        $author_email = get_the_author_meta( 'user_email', $author_id );
        $post_title = $post->post_title;
        $post_link = get_permalink( $post->ID );

        $subject = esc_html__( 'Your Post Has Been Published', 'text-domain' );

        $message = "Dear {$author_display_name},

            We're thrilled to inform you that your post, '{$post_title}', has been approved and is now live on our website. You can view your post here: {$post_link}.

            Congratulations! Your post is now visible to our readers, and we look forward to your continued contributions.

            Regards,";

        // Send the email.
        wp_mail( $author_email, $subject, $message );
    }
}

This code hooks into the “transition_post_status” action, triggering our custom function when a post’s status changes. It checks if the transition is from “draft” to “publish” for the “post” post type. If these conditions are met, an email is sent to the post author, notifying them of the publication.

By utilizing appropriate hooks like “transition_post_status,” we can extend WordPress functionality and automate actions based on post status changes.