Custom notifications in BuddyPress

Здесь просто перевод статьи про собственные уведомления в buddybar.

Not so long ago I needed to show my own custom notifications in buddybar of one WP + BuddyPress site that I developed. The first thing I did was googling for the answer, and know what? I found nothing.  Weeell, this is why I both like and dislike BuddyPress. You have to investigate everything and mess about the code on your own but at the same time challenge is so captivating.

Spoiler: yes, I managed to do it =)

For starters I looked into the wp_bp_notifications table in order to figure out how it all is arranged there and found the following fields:
id, user_id (for whom the notification is), item_id, secondary_item_id, component_name, component_action , date_notified, is_new

At first I didn't understand what component_name and component_action are for. When sending messages there appeared a record with values 'messages' and 'new_message' accordingly. But when I tried to insert something else like 'members' and 'new_thanks' the notification didn't appear, which made me dig deeper. I wanted to figure out what component is and what action it does.

If you open /wp-content/plugins/buddypress/bp-core/bp-core-loader.php you will see that components can be optional or required:

$bp->optional_components = apply_filters( 'bp_optional_components', array( 'activity', 'blogs', 'forums', 'friends', 'groups', 'messages', 'settings', 'xprofile' ) );
$bp->required_components = apply_filters( 'bp_required_components', array( 'members' ) );

There's no need to create a new component (and I'm not looking forward to it), that's why I decided to use the members component. It makes no difference which one to use, it only must be enabled (for example Friend connections and Activity stream were disabled on my site). In general I just needed to show a short message "You've been thanked for your comment!", kind of "Like" on Facebook, so it wasn't a big deal for me.

Right away I decided not to write some doubtful hacks but to do it neatly, so I will not describe the first variant of the possible solutions I could use; my final solution implies that the component object has a defined variable notification_callback - a function which is called when a new entry appears in the database (with component_name = members in my case).

If we compare /wp-content/plugins/buddypress/bp-activity/bp-activity-loader.php with /wp-content/plugins/buddypress/bp-members/bp-members-loader.php, we'll see that the $globals variable of the first one has 'notification_callback', but it's not specified at all in the second one; that was exactly the reason of my confusion at first, but now I know what the point is, so don't bother looking through the code, I'll share it with you anyway ;)

Finally, all we have to do is indicate the name of the function that we are going to use as a callback (the one that will be called each time Wordpress finds a record of a certain type in the notifications table), and just write this function.

As a result bp-members-loader.php will contain similar code in setup_globals() function:

$globals = array( 
            'path'          => BP_PLUGIN_DIR, 
            'slug'          => BP_MEMBERS_SLUG, 
            'root_slug'     => isset( $bp->pages->members->slug ) ? $bp->pages->members->slug : BP_MEMBERS_SLUG, 
            'has_directory' => true, 
            'search_string' => __( 'Search Members...', 'buddypress' ), 
            'notification_callback' => 'bp_members_format_notifications', // here we indicate our function 

And then we add bp_members_format_notifications() to bp-members-functions.php; I simply copied it from bp-activity-functions.php (there was bp_activity_format_notifications) and rewrote it the way I needed. Incidentally, you can insert certain values for item_id and secondary_item_id, they will be passed to the function as parameters. So it looked like this:

function bp_members_format_notifications( $action, $item_id, $secondary_item_id, $total_items, $format = 'string' ) { 
    global $bp; 
    switch ( $action ) { 
        case 'new_thanks': 
            // EXAMPLE of using $item_id and $secondary_item_id 
            $thanks_for      = $item_id; 
            $who_thanked     = $secondary_item_id; 
            // then you can use these variables to format output; I didn't do it in this example 
            $link = '/members/'.$bp->loggedin_user->userdata->user_nicename.'/'; 
            $return = '<a href="'.$link.'">You\'ve been thanked!</a>'; 
    return $return; 

This is it! Now the notifications will appear in buddybar, and they can easily be edded or deleted with the help of functions
bp_core_delete_notifications_by_type($user_id, $component_name, $component_action);
bp_core_add_notification( $item_id, $user_id, $component_name, $component_action, $secondary_item_id = 0, $date_notified = false );

I hope you find this information helpful. If you don't understand anything feel free to drop a comment.

 Жду с нетерпением
ваших комментариев!

Подписаться на RSS

Вы можете нажать "подписаться", чтобы следить за моими новостями!
Так вы всегда будете в курсе появления новостей на сайте =)
О том, что такое RSS можно прочитать здесь.


Подписаться на Twitter

Я специально зарегистрировался в Твиттере, чтобы вы могли следить за обновлениями на сайте =)


Блог чисто поржать Это блог моего брата. Пишет он там полный бред =) В общем, можете сами зайти убедиться в этом.
Envato marketplace А эти люди занимаются прокатом карнавальных костюмов и масок в Минске. К слову, я им делал сайт.