1

I have created an Add / Remove Dynamic input fields. I am using wp_mail(); to send mails. I have restricted the first user from receiving mail. I want to send mail to other users. Everything is working properly. The only problem is that every user is getting double emails. wp_mail(); creates it twice at same time.

Means when I submits the form each user receives same email twice. I want each user should receive one email only. Following is my code :

<?php get_header(); ?>

<?php

$member_details->user_email = array_map( 'sanitize_text_field', $_POST['user_email'] );
$member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] );
$member_details->status = array_map( 'sanitize_text_field', $_POST['status'] );

if ( isset( $_POST['project_prev'] ) ) {

$user_emails = $member_details->user_email;
$user_statuses = $member_details->status;

for ($i=1; $i < count($user_emails); $i++) { 
    $user_email1[] = $user_emails[$i];

}

for ($a=1; $a < count($user_statuses); $a++) { 
    $user_status = $user_statuses[$a];

if ( $user_status == 'Unverified' ) {

$to = $user_email1;
$subject = "Congrats! You are added to the Project  -  " . "'" . $project_title . "'";
$message = 'If you are not the member of project plz contact us to remove at mineshrai@gmail.com';

wp_mail( $to, $subject, $message ); 

}

}

}

?>

<form method="POST">

<div class="panel panel-default">

  <div class="panel-heading"><center><b>Team Members</b></center></div>

  <div class="panel-body">

    <div class="row">

      <div class="col-md-5"><label>Member's Registered Email</label></div>
      <div class="col-md-5"><label>Role in Project</label></div>
      <div class="col-md-2"></div>

    </div>

    <div class="row">

      <div class="col-md-5">

        <div class="form-group">

          <input type="text" class="form-control" name="user_email[]" value="<?php $current_user = wp_get_current_user(); if ( !($current_user instanceof WP_User) ) return; echo $current_user->user_email; ?>" placeholder="" readonly="readonly">

        </div>

      </div>

      <div class="col-md-5">

        <div class="form-group">

          <input type="text" class="form-control" name="user_role[]" placeholder="">
          <input type="hidden" class="form-control" name="status[]" value="Verified" placeholder="">

        </div>

      </div>

      <div class="col-md-2">

        <button type="button" class="btn btn-success" id="add-member-fields"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add</button>

      </div>

    </div>

    <div id="member-fields">

    </div>

<p class="help-block"><i>To add member please register new User, if already not registered.</i></p>

  </div>

</div>

<input class="btn btn-info btn-block" type="submit" name="project_prev" value="Preview" style="border-radius: 0px;">

</form>

<?php

$user = wp_get_current_user();
$args = array(
  'role'         => 'backer',
  'exclude'      => array( $user->ID ),
 );

$users = get_users( $args );
$get_user_emails = wp_list_pluck( $users, 'user_email' );

?>

<script type='text/javascript'>

jQuery(document).ready(function($) {
  var wrapper = $("#member-fields");
  var add_button = $("#add-member-fields");

  var x = 1;
  var availableAttributes = <?php echo json_encode($get_user_emails); ?>;
  var previousValue="";

  add_button.click(function(e) {
    e.preventDefault();
    x++;
    var element = $('<div id="user-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" id="user_email" name="user_email[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="status[]" value="Unverified" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove_member_field"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>');

    element.fadeIn("slow").find("input[name^='user_email']").autocomplete({
    autoFocus: true,
      source: availableAttributes,
    });
    wrapper.append(element);
  });

  wrapper.on("keyup","#user_email",function() {
    var isValid = false;
    for (i in availableAttributes) {
        if (availableAttributes[i].toLowerCase().match(this.value.toLowerCase())) {
            isValid = true;
        }
    }
    if (!isValid) {
        this.value = previousValue
    } else {
        previousValue = this.value;
    }

});

  wrapper.on("click", "#remove_member_field", function(e) {
    e.preventDefault();
    $(this).parent().fadeOut(300, function() {
      $(this).closest('#user-fields').remove();
      x--;
    });
  });
});

</script>

<?php get_footer(); ?>
7
  • Which file is that in your question? Also how do you verify that an email doesn't appear in $user_emails more than once? Where does the $member_details variable come from? Is it just used without ever creating it? Can you fix the indentation?
    – Tom J Nowell
    Jul 24, 2018 at 13:23
  • @TomJNowell yes the print_r($user_emails); verifies that email appears only once. $member_details is just used and not created earlier...
    – Minesh
    Jul 24, 2018 at 13:29
  • 2
    Did you try to add break; after/below the wp_mail( $to, $subject, $message ); or maybe do $user_statuses = array_unique( $member_details->status );?
    – Sally CJ
    Jul 24, 2018 at 13:39
  • @SallyCJ ur code is working but has an issue. I want mail to be send to only those users whose status are 'Unverified'. Verified users should not get any mail. Inthis case until the last user is Unverified, all the users are receiving mail.
    – Minesh
    Jul 24, 2018 at 14:14
  • @Minesh Sally is right though, for each user with an unverified status you send an email, but you always send to the same address, so if there are 5 unverified users, rather than 1 email each to 5 users, you get 5 emails each to every single user, that's 5x5 emails or 25 emails total sent
    – Tom J Nowell
    Jul 24, 2018 at 14:49

2 Answers 2

1

These POST variables: $_POST['user_email'], $_POST['user_role'], and $_POST['status'] (which each is an array) are connected to each other by their index, hence you can loop through just one of them and use the same index (or iterator) to access the items in the other arrays.

This should help you understand it:

for ( $i = 0; $i < count( $member_details->user_email ); $i++ ) {
    $user_email = $member_details->user_email[ $i ];
    $user_role = $member_details->user_role[ $i ];
    $status = $member_details->status[ $i ];
    ...
}

So this part/code:

if ( isset( $_POST['project_prev'] ) ) {

$user_emails = $member_details->user_email;
$user_statuses = $member_details->status;

...

}

I coded it like this:

(Note that I re-indented it for clarity.)

if ( isset( $_POST['project_prev'] ) ) {

    // Starts with the first user (index 1).
    for ( $i = 1; $i < count( $member_details->user_email ); $i++ ) {
        $user_status = $member_details->status[ $i ];

        if ( $user_status === 'Unverified' ) {

            $to = $member_details->user_email[ $i ];
            $project_title = '??'; // This wasn't defined anywhere in the file/code.
            $subject = "Congrats! You are added to the Project  -  " . "'" . $project_title . "'";
            $message = 'If you are not the member of project plz contact us to remove at mineshrai@gmail.com';

            wp_mail( $to, $subject, $message );

        }

    }

}
1
  • Not a problem. I'm glad it helped you. 🙂
    – Sally CJ
    Jul 25, 2018 at 4:59
0

The problem here is, you first create an array of all the email addresses, and then in your second "for" loop for user statuses, if the current user's status in the loop is unverified, you send an email to the entire array $user_email1. If it's safe to assume that $i refers to the same user in both the $user_email1 array and the $user_statuses array, you can just change

$to = $user_email1;

to

$to = $user_email1[$i];

and that way you're only sending the email to the current user in your for loop.

2
  • $to = $user_email1 is out of loop and adding [$i] has stop sending mails.
    – Minesh
    Jul 24, 2018 at 13:37
  • Try a var_dump or print_r() on it after the loop. It's still an array after the for loop but since you're not sharing how any of the values are set they may be in a slightly different format than you're expecting.
    – WebElaine
    Jul 24, 2018 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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