Need help sending out Buddypress custom notifications, please

I want to send notifications using BuddyPress to users with different fields. For example, I have a profile field called: Science and a field called Business. I want to send messages only to people who have selected Business.

These fields are Buddypress profile fields

  • Ash

    Hello there

    You would need a value of profile field to get users. For example, I assume your field name is business and value is xyz. Then you can try this code:

    function get_desired_users($field_id, $field_val) {
        //$field_id: (int) this is the ID of the field you'd like to check against
        //$field_val: (str) this is the value you want those users to have in the field
    
        global $wpdb;
        $bp_table = $wpdb->prefix . 'bp_xprofile_data'; 
    
        $query = $wpdb->prepare(
            "SELECT U.user_email " .
            "FROM $bp_table B, $wpdb->users U " .
            "WHERE B.user_id = U.ID " .
            "AND B.field_id = %d " .
            "AND B.value = %s"
           , $field_id
           , $field_val
        );
    
        $get_desired = $wpdb->get_results($query);
    
        if(count($get_desired)) {
            return $get_desired;
        } else {
            return false;
        }
    }
    
    $users = get_desired_users( 'business', 'xyz' );
    
    foreach( $users as $user )
    {
        wp_mail(
            $user->user_email,
            'Subject',
            'Body'
        );
    }

    Hope it helps! Please feel free to ask more questions if you have any.

    Have a nice day!

    Cheers,
    Ash

  • Ash

    Hello Mwale

    The following line get the users:

    $users = get_desired_users( 'business', 'xyz' );

    This will get users whose xprofile field business has a value called xyz.

    Then these lines of code send the email to all users:

    foreach( $users as $user )
    {
        wp_mail(
            $user->user_email,
            'Subject',
            'Body'
        );
    }

    In the above code, you can see Subject - that is your email subject, and Body - that is your email body content. So you can make the adjustment in there.

    Have a nice day!

    Cheers,
    Ash