# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Users](https://wpide.com/library/category/users/)
- Tags: buddypress, messages, privacy
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/buddypress-friends-only-messages/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "BuddyPress: Only Friends Can Send Private Messages" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
