March 5, 2025
1 min read

How the Code Works

The email notification system is built around three core components:

  1. Email Sending Function (send_post_approval_email)
    • Retrieves post and author details
    • Generates a dynamic email template
    • Handles placeholder replacements
    • Sends email using WordPress’s wp_mail() function
  2. Automatic Trigger (auto_trigger_post_approval_emails)
    • Hooks into WordPress’s post status transitions
    • Checks if the post type is eligible for notification
    • Triggers email sending when post is published
  3. Placeholder Replacement
    • Dynamically replaces {{Placeholders}} with actual content
    • Supports flexible template customization

Workflow Breakdown

// 1. Retrieve Post and Author Details
$post = get_post($post_id);
$author = get_userdata($post->post_author);

// 2. Generate Post Link
$post_link = get_permalink($post_id);

// 3. Prepare Email Template
$message = str_replace(
    ['{{First Name}}', '{{Item Name}}', '{{Post Link}}', '{{Website URL}}'],
    [$author->user_login, $post->post_title, $post_link, get_site_url()],
    $default_template
);

// 4. Send Email
wp_mail($author->user_email, $subject, $message, $headers);

Key Features

  • Supports multiple post types
  • Customizable email templates
  • Automatic permalink insertion
  • Flexible sender configuration

Full Implementation Code

functions.php
<?php
/**
 * Send customizable email notification when a post is published
 *
 * @param int $post_id The ID of the post being published
 * @param string $email_subject Optional custom email subject
 * @param string $email_template Optional custom email template
 * @param string $from_email Optional custom sender email
 * @param string $from_name Optional custom sender name
 */
function send_post_approval_email(
    $post_id, 
    $email_subject = null, 
    $email_template = null, 
    $from_email = null, 
    $from_name = null
) {
    // Get post details
    $post = get_post($post_id);
    
    // Bail if post doesn't exist
    if (!$post) {
        return;
    }

    // Get post author details
    $author = get_userdata($post->post_author);
    
    // Bail if no author found
    if (!$author) {
        return;
    }

    // Get post permalink
    $post_link = get_permalink($post_id);

    // Default subject if not provided
    $subject = $email_subject ?? 'Your Listing is Now Live!';

    // Default email template if not provided
    $default_template = "Hi {{First Name}},

Your listing '{{Item Name}}' has been approved and is now live.

View your listing: {{Post Link}}

If you have any questions, please contact us.

Best regards,
The Team
{{Website URL}}";

    // Use provided template or default
    $message = $email_template ?? $default_template;

    // Replace placeholders
    $message = str_replace(
        [
            '{{First Name}}', 
            '{{Item Name}}', 
            '{{Post Link}}',
            '{{Website URL}}'
        ], 
        [
            $author->user_login, 
            $post->post_title, 
            $post_link,
            get_site_url()
        ],
        $message
    );

    // Prepare from email
    $default_from_email = get_option('admin_email');
    $default_from_name = get_option('blogname');

    // Email headers
    $headers = array(
        'Content-Type: text/plain; charset=UTF-8',
        sprintf(
            'From: %s <%s>', 
            $from_name ?? $default_from_name, 
            $from_email ?? $default_from_email
        )
    );

    // Send the email
    wp_mail($author->user_email, $subject, $message, $headers);
}

/**
 * Automatically trigger email for specific post types
 */
function auto_trigger_post_approval_emails($new_status, $old_status, $post) {
    // Only trigger when post moves from draft/pending to published
    if ($old_status !== 'publish' && $new_status === 'publish') {
        // List of post types you want to trigger emails for
        $eligible_post_types = [
            'post',      // Standard blog posts
            'agency',    // Your specific custom post type
            'product',   // WooCommerce products
            'listing'    // Any custom listing type
        ];

        // Check if current post type is in the eligible list
        if (in_array($post->post_type, $eligible_post_types)) {
            // Send generic approval email
            send_post_approval_email($post->ID);
        }
    }
}
add_action('transition_post_status', 'auto_trigger_post_approval_emails', 10, 3);

/**
 * Example of custom post type specific email
 */
function custom_agency_approval_email($post_id) {
    send_post_approval_email(
        $post_id,
        'Your Agency Listing is Live!', 
        "Custom agency-specific template...", 
        'agency@yoursite.com', 
        'Agency Team'
    );
}
// Uncomment and modify as needed
// add_action('publish_agency', 'custom_agency_approval_email', 10, 1);

Advanced Usage Examples

Customizing for Specific Post Types

// Agency-specific notification
add_action('publish_agency', function($post_id) {
    send_post_approval_email(
        $post_id,
        'Agency Listing Approved',
        "Specialized agency listing template...",
        'agency@notifications.com'
    );
}, 10, 1);

Adding Conditional Logic

function advanced_notification_handler($new_status, $old_status, $post) {
    // Custom conditions before sending email
    if ($new_status === 'publish' && 
        some_custom_validation_function($post)
    ) {
        send_post_approval_email($post->ID);
    }
}

Implementation Tips

  • Add to theme’s functions.php
  • Customize $eligible_post_types
  • Test thoroughly with different post types
  • Consider performance impact on large sites

Debugging

  • Check email delivery
  • Verify post-type triggers
  • Test with various user roles

Leave a Reply

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

ACF

Filter custom post type by Custom Field (ACF) in the admin area

Show filter on custom post type admin area with custom field value

WordPress Next and Previous Post

WordPress Next and Previous Post navigation for custom post type and defult blog post simple php code to use single page

Add custom Elementor widgets in the Hello child theme

learn how to add custom Elementor widgets to the Hello child theme.

PHP

File manager for any website

You can install a File manager for any website you are working on. It simple file manager PHP script that made by Tiny File Manager

Web Development Project in mind?

if you looking for a web developer for paid contribution to your project I am available for work.

Mukto
Mukto

Click the button below to chat with me.