Search code examples
phpwordpresswoocommerceproductemail-notifications

Send email to users who finished submitting a product review in WooCommerce


I am using the following code which works fine.

function send_comment_email_notification( $comment_ID, $commentdata ) {
    $comment = get_comment( $comment_id );
    $postid = $comment->comment_post_ID;
    $master_email = '[email protected]';
    var_dump($commentdata);
    if( isset( $master_email ) && is_email( $master_email ) ) {
        $message = 'New comment on <a href="' . get_permalink( $postid ) . '">' .  get_the_title( $postid ) . '</a>';
        add_filter( 'wp_mail_content_type', create_function( '', 'return "text/html";' ) );
        wp_mail( $master_email, 'New Comment', $message );
    }
}
add_action( 'comment_post', 'send_comment_email_notification', 11, 2 );

However, I would like to send an email to the user who just reviewed on a product page so I can offer them a coupon and a thank you for giving a review.

The problem is the $master_email variable, that is "hard coded". I need to capture the email entered by the user after he/she submitted the product review

Any advice?


Solution

  • To get the email entered by the user after he/she submitted the product review, you can use $commentdata['comment_author_email']

    So you get:

    function action_comment_post( $comment_ID, $comment_approved, $commentdata ) {  
        // Isset
        if ( isset ( $commentdata['comment_author_email'] ) ) {
            // Get author email
            $author_email = $commentdata['comment_author_email'];
    
            if ( is_email( $author_email ) ) {
                // Post ID
                $post_id = $commentdata['comment_post_ID'];
                
                // Send e-mail
                $to = $author_email;
                $subject = 'The subject';
                $body = sprintf( __(' Thank you for giving a review on %s', 'woocommerce' ), '<a href="' . get_permalink( $post_id ) . '">' .  get_the_title( $post_id ) . '</a>' );
                $headers = array( 'Content-Type: text/html; charset=UTF-8' );
                
                wp_mail( $to, $subject, $body, $headers );
            }
        } 
    }
    add_action( 'comment_post', 'action_comment_post', 10, 3 );