BuddyPress: Only Friends Can Send Private Messages
Limits BuddyPress private messages so members can only message people who have accepted their friend request, which cuts down unwanted messages.
Opens WPIDE on
Code
if ( ! function_exists( 'buddypress' ) ) {
return;
}
add_action( 'messages_message_before_save', function ( $message ) {
if ( ! bp_is_active( 'friends' ) || empty( $message->recipients ) || user_can( (int) $message->sender_id, 'bp_moderate' ) ) {
return;
}
foreach ( (array) $message->recipients as $key => $recipient ) {
$recipient_id = is_object( $recipient ) ? (int) $recipient->user_id : (int) $recipient;
if ( $recipient_id !== (int) $message->sender_id && ! friends_check_friendship( (int) $message->sender_id, $recipient_id ) && ! user_can( $recipient_id, 'bp_moderate' ) ) {
unset( $message->recipients[ $key ] );
}
}
} );
Notes
Moderators can still message anyone. If none of the recipients are friends the message is not sent and BuddyPress shows its error notice.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.