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 = 'example@mail.com';
        $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 <support@example.com');

        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?

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 = 'example@mail.com';
    $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 <support@example.com');

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

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

To learn more about this hook, check the Docs.

  • I'm glad it worked for you :)... could you pelase mark that as the correct answer, thanks ! – Cesar Henrique Damascena Jul 31 '17 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 = 'example@mail.com';
    $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 <support@example.com');

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

add_action( 'wp_login', 'InvioMail');

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.