1

i tried to create a simple function to receive a email when a specify user is logged, i tried with $current_user->ID and also with wp_get_current_user() but not working. This is my code:

function InvioMail() {
     global $current_user;
   $ID = $current_user->ID;
    $user = wp_get_current_user();
  $name = $user->user_login;

    if ($name == 'piero') {

        $to = '[email protected]';
        $subject = 'test su action hook wp_login';
        $body = 'test su action hook pwp_login';
        $headers = array('Content-Type: text/html; charset=UTF-8','From: My Site Name <[email protected]');

        wp_mail( $to, $subject, $body, $headers );
    }
}

add_action( 'wp_login', 'InvioMail');

Without if condition work property but when i try with IF nothing.

Where I'm wrong?

2 Answers 2

3

This should work for you, make sure that the user_login or user_id matches to the string you're using in the condition. Try to do a var_dump($user_login);

And about the function you're using, you don't need to grab the global or call get_current_user();, because the action you're calling already pass two parameters to your function, the first is a string with the $user_login, and the second is a WP_User object the current logged in user.

To use it, just change your code to this:

function InvioMail($user_login, $user) {

  if ($user_login == 'piero') {

    $to = '[email protected]';
    $subject = 'test su action hook wp_login';
    $body = 'test su action hook pwp_login';
    $headers = array('Content-Type: text/html; charset=UTF-8','From: My Site Name <[email protected]');

    wp_mail( $to, $subject, $body, $headers );
  }
}

add_action( 'wp_login', 'InvioMail', 10, 2);

To learn more about this hook, check the Docs.

1
  • I'm glad it worked for you :)... could you pelase mark that as the correct answer, thanks ! Commented Jul 31, 2017 at 13:27
0

Try the code below.

function InvioMail() {
  global $current_user;

  if ($current_user->ID == 1){ // change id 1 to your user id 

    $to = '[email protected]';
    $subject = 'test su action hook wp_login';
    $body = 'test su action hook pwp_login';
    $headers = array('Content-Type: text/html; charset=UTF-8','From: My 
    Site Name <[email protected]');

    wp_mail( $to, $subject, $body, $headers );
   }
}

add_action( 'wp_login', 'InvioMail');
1

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.