How to send email notification to admin if comment is made on custom post?

How to send email notification to admin if comment is made on custom post?

Recieve Email Notifications for Comments

From Settings » Discussion page you can set the options to receive email notifications whenever someone leaves comment on your website, or a comment is waiting to be approved. Checking these options will also send you email notification when a website sends you trackback or pingback. However, you will not receive any email notifications for comments or trackbacks marked as spam and caught by Akismet plugin.

If you do not receive email notifications after enabling these checkboxes, then please check the email address in Settings » General page, to make sure it is correct. If the email address is correct then check your Spam folders. Sometimes web based email service providers, particularly Gmail mark messages spam if their systems suspect that the email may not have originated from the domain it claims to be originated from. However, once you mark the message as Not Spam in gmail, you will start receiving notifications in your inbox.

Recieve Email Notifications for Comments on Custom Posts

WordPress sends email to the Admin by default if a comment is made on default posts. But for the custom posts, we may have to handle it on our own way.

Assume, we have a custom post ‘trip’ (say). If someone comments on any of the ‘trip’ posts, then admin should get an email notification.

Below we have a function that is hooked in an action ‘comment_post’. This hook runs while comment is posted in that post. By the use of this hook, we can easily run any function while the comment is being posted.

class stdObject
function init()
add_action( 'comment_post', array( $this,'wpte_comment_email_notification' ), 11, 2 );

function wpte_comment_email_notification($comment_ID, $comment_approved) {
$post_type = get_post_type();
if ($post_type !== 'trip') { //if the post not a trip post, return
$comment = get_comment($comment_ID);
$post_ID = $comment->comment_post_ID;
$author_ID = get_post_field( 'post_author', $post_ID );
$author_email = get_option( 'admin_email' );
if (isset($author_email)) {
$message = 'New comment on <a href="' . get_permalink($post_ID) . '">' .
get_the_title($postid) . '</a>';
add_filter('wp_mail_content_type',create_function('', 'return "text/html";'));

$postID = wp_insert_post( $new_page );
wp_mail($author_email, 'New Comment', $message);
$obj = new stdObject;

Leave comment

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