Buddypress send email notification only if user is not logged in

When a member send a message to another member, the recipient receive a message in buddypress and also an email.

I want to change that because if you receive many messages, you have too much mail in your mailbox even if you are logged in : I want to receive mail only if I am not logged in buddybress.

Read More

I have find where adding the code but I don’t know how to hooks (add_action or add_filter)
The file is : wp-content/plugins/buddypress/bp-messages/bp-messages-notifications.php

and the modification is at the end of file, just adding the if test before sending email :

if (!is_user_online($recipient->user_id)) {
     wp_mail( $email_to, $email_subject, $email_content );
}

How I can do this without change the core file of buddypress ?

Related posts

Leave a Reply

1 comment

  1. One thing you can do is to filter $email_to and return empty string if the recipient is logged in. This way wp_mail() will fail to send the message and return false. Add the following to theme functions.php or to bp-custom.php file:

    add_filter('messages_notification_new_message_to', 'disable_loggedin_email_notification');
    function disable_loggedin_email_notification($email_to) {
        $user = get_user_by('email',$email_to);
        if (bp_has_members("type=online&include=$user->ID")) {
            $email_to = '';
        }
        return $email_to;
    }
    

    EDIT: A possible solution for your case with the plugin you use is to get all the users who have that e-mail and check if any is online by passing that list to bp_has_members() function:

    add_filter('messages_notification_new_message_to', 'disable_loggedin_email_notification');
    
    function disable_loggedin_email_notification($email_to) {
        $users = get_users(array(
            'search' => $email_to
        ));
        $ids = array();
        foreach ($users as $user) {
            $ids[] = $user->ID;
        }
        $ids = implode(',', $ids);
        if (bp_has_members("type=online&include=$ids")) {
            $email_to = '';
        }
        return $email_to;
    }