Search code examples
wordpresswoocommercecommentsreview

How can I add a check and not send an auto-reply to certain comments if the user fills in a custom field?


I'm using custom fields in the comment form "Did you like this book?" and "yes" and "no" values. I want to send 2 different auto-replies to a comment, if the user selects "yes" then the response is "Thank you for your kind recognition, customer's satisfaction is always our goal." and if "no" then the auto answer is "We'll strive to do better." I would appreciate any of your help...

//And this is how I send an auto reply to a comment
add_action( 'comment_post', 'author_new_comment', 10, 3 );
function author_new_comment( $comment_ID, $comment_approved, $commentdata ){
    $comment_parent = (int) $commentdata['comment_parent'];
    
    // If a new comment is a reply to another comment, don't do anything
    if ( $comment_parent !== 0 ) {
        return;
    } 
    //How do I add a response if the comment contains the value of the [likebook ] meta field???
    if( !empty( $_POST['likebook'] ) {
return;
    }
    
    $commentdata = [
        'comment_post_ID'      => $commentdata['comment_post_ID'],
        'comment_author'       => 'admin',
        'comment_author_email' => '[email protected]',
        'comment_author_url'   => 'http://example.com',
        'comment_content'      => 'Thank you for your kind recognition, customer satisfaction is always our goal.',
        'comment_type'         => 'comment',
        'comment_parent'       => $comment_ID,
        'user_ID'              => 1,
    ];
  
    wp_new_comment( $commentdata );
}

Solution

  • try these,

    add_action( 'comment_post', 'author_new_comment', 10, 3 );
    function author_new_comment( $comment_ID, $comment_approved, $comment ) {
        if ( $comment['comment_parent'] !== 0 ) {
            return;
        }
        
        if ( ! empty( $_POST['like'] ) ) {
            if ( $_POST['like'] == 'dog' ) {
                $msg = 'We are glad that you liked it!';
            } else {
                $msg = 'We will try to make this product better!';
            }
            
            $admins       = get_super_admins();
            $current_user = get_user_by( 'login', $admins[0] );
            
            $data = array(
                'comment_post_ID'      => $comment['comment_post_ID'],
                'comment_content'      => $msg,
                'comment_parent'       => $comment_ID,
                'user_id'              => $current_user->ID,
                'comment_author'       => $current_user->user_login,
                'comment_author_email' => $current_user->user_email,
                'comment_author_url'   => $current_user->user_url
            );
            
            $comment_id = wp_insert_comment( $data );
            if ( is_wp_error( $comment_id ) ) {
                throw new Exception( $comment_id );
            }
        }
    }