For my website, I need to send an email to all users every time someone posted something on the blog wall (I am using BuddyPress and Youzify).
For that I wrote a function in function.php, but the problem is that I have a lot of users (around 300), so when someone poste something there is a very long loading and after some time there is a 524 error in the console.
If I reload the page, the new post is here but emails are not sent.
function send_email_to_all_users($activity_array, $activity_id) {
//get the post user's id
$username = bp_core_get_username( $activity_array['user_id']);
//get the link of the new post
$view_link = bp_get_root_domain() . '/' . bp_get_activity_root_slug() . '/p/' . $activity_id;
//get every user but not the one who posted
$users = BP_Core_User::get_users( array(
'type' => 'alphabetical',
'exclude' => array( $activity->user_id ),
) );
//for every user send an email
foreach ( $users['users'] as $user ) {
$to = $user->user_email;
$subject = 'mail test subject';
$message = $username . " published <br> You can see " . $username . ', post here: ' . $view_link;
wp_mail( $to, $subject, $message );
}
}
add_action( 'bp_activity_add', 'send_email_to_all_users', 10, 4 );
When I tried with only one email it worked well
function send_email_to_all_users($activity_array, $activity_id) {
//get the post user's id
$username = bp_core_get_username( $activity_array['user_id']);
//get the link of the new post
$view_link = bp_get_root_domain() . '/' . bp_get_activity_root_slug() . '/p/' . $activity_id;
$to = '[email protected]';
$subject = 'mail test subject';
$message = $username . " published <br> You can see " . $username . ', post here: ' . $view_link;
wp_mail( $to, $subject, $message );
}
add_action( 'bp_activity_add', 'send_email_to_all_users', 10, 4 );
Does anyone have an idea how to fix this ?
2
Answers
For people having the same problem as me, here is an update. As Alex Howansky and Anan suggested, I installed a queue plugin on wordpress. I installed "Mail Queue" from WDM. I also changed my code as shanebp suggested. I also contacted my host's support and it turns out that I had several configuration problems. Now everything works perfectly, thanks for all your help !
Hope this can help!
300 emails is not that many, unless you have ‘weak’ hosting or have a lot of concurrent activity posts.
Some hosting companies limit the number of emails that can be sent per day, per hour, etc. Ask your host.
The queue plugins may help, but you could speed up your filter function…
This is very inefficient for your needs:
$users = BP_Core_User::get_users...
It gathers all kinds of thing you do not need. All you need are the email addresses. And the order does not matter.
All you need is the WP function get_users.
For example, something like this:
If you really need to prevent the author from receiving an email, get their email first:
And then use unset to remove it from the
$users
array before you start the loop.