Search code examples
phpmysqlwordpressbuddypress

BuddyPress, send notification when new stories are posted


I have setup BuddyPress with a custom profile field that lists check boxes for tags related to my site.

Is there a way to send automatic notifications to registered BuddyPress users based on their custom profile field selection whenever a new post goes up?


Solution

  • The save_post hook can help you out.

    http://codex.wordpress.org/Plugin_API/Action_Reference/save_post

    Something along the lines of:

    function send_bp_message( $post_id ) 
    {
      //verify post is not a revision
      if( wp_is_post_revision($post_id) )
      {
        return;
      }
    
      // get the user ids you want to notify
      global $bp, $wpdb;
    
      $custom_field_id = 1; // the profile field you want to check
      $custom_field_value = 'true'; // the value you're looking for
    
      $stmt = $wpdb->prepare("
        SELECT
          {$bp->profile->table_name_data}.user_id
        FROM
          {$bp->profile->table_name_data}
        LEFT JOIN
          {$bp->profile->table_name_fields} ON {$bp->profile->table_name_fields}.id = {$bp->profile->table_name_data}.field_id
        WHERE
          {$bp->profile->table_name_fields}.id = %d
        AND
          {$bp->profile->table_name_data}.value LIKE %s
      ", $custom_field_id, $custom_field_value);
    
      $recipient_ids = $wpdb->get_col($stmt); // array of matched user ids
    
      // send buddypress notification to matched user ids
      // (you could loop through $recipient_ids to send individual notifications)
      $msg_args = array(
        'sender_id' => 1, // 1 = admin
        'recipients' => $recipient_ids,
        'subject' => 'New post',
        'content' => 'A new post has been created...'
      );
      $thread_id = messages_new_message($message_args);        
    }
    add_action('save_post', 'send_bp_message');