0

I use the code below to customize the email notifications of new comments sent to the post author. This works fine for unmoderated comments, but not for moderated ones.

In general, all comments are automatically approved, excepting those that contain multiple links. These comments are retained for moderation by administrator (not by post author). After approval the post author receives a notification as usual, but omitting my customization. How can this be avoided or fixed?

// This fires before a comment is posted
add_action( 'pre_comment_on_post', function( $post_id ) {

    if( 'cpt_here' !== get_post_type( $post_id ) ) { return; }

    add_filter( 'comment_notification_text', function( $notify_message, $comment_id ) {
        $comment_obj = get_comment( $comment_id );

        $message = 'You have received a message from user ' . $comment_obj->comment_author . "\r\n\r\n";

        $message .= 'Message:' . "\r\n" . $comment_obj->comment_content . "\r\n\r\n\r\n";
        $message .= 'You can reply to this message here: ' . get_comment_link( $comment_id );

        // customize subject of comment notifications sent to post author
        add_filter( 'comment_notification_subject', function() use ( $comment_obj ) {
            return 'You have a message from ' . $comment_obj->comment_author;
        } );

        // customize email address of comment notifications sent to post author
        add_filter( 'wp_mail_from', function( $original_email_address ) {
            return '[email protected]';
        } );

        // customize sender name of comment notifications sent to post author
        add_filter( 'wp_mail_from_name', function( $original_email_from ) {
            return 'noreply';
        } );

        return $message;
    }, 10, 2 );

} );

1 Answer 1

0

Initially it seemed like a good idea to add comment_notification_text inside the pre_comment_on_post hook, but it didn't go well. So I removed the pre_comment_on_post and just added to comment_notification_text a comment type check, which is related to the CPT for which the comments are. Now my code works fine for both comment categories (moderated and not).

add_filter( 'comment_notification_text', function( $notify_message, $comment_id ) {
    if( 'message' !== get_comment_type( $comment_id ) ) { return $notify_message; }

    // the rest of the code

    return $message;
}, 10, 2 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.