9

When an user upload an new avatar, the avatar is posted in the activity wall. How can I get this activity ID by using the userId?

I think the only way is to create an own query, right?

arghtype
  • 4,376
  • 11
  • 45
  • 60
Peter
  • 11,413
  • 31
  • 100
  • 152

1 Answers1

6

You can write a query to get that activity. There is also a filter you can hook into which will get called after the avatar is uploaded (explained later):

<?php

global $wpdb;

$query = "SELECT * FROM {$wpdb->prefix}bp_activity WHERE " .
         "`type` = 'new_avatar' AND `user_id` = %d " .
         "ORDER BY `date_recorded` DESC LIMIT 1";

$result = 
$wpdb->get_row(
    $wpdb->prepare($query, $user_id)
);

if ($result) {
    // found an activity item for avatar upload
    var_dump($result);
} else {
    // user has not uploaded an avatar
}

Result looks like:

stdClass Object
(
    [id] => 2   <-- this is the activity ID
    [user_id] => 1
    [component] => profile
    [type] => new_avatar
    [action] => admin changed their profile picture
    [content] => 
    [primary_link] => http://example.com/wordpress/members/admin/
    [item_id] => 0
    [secondary_item_id] => 0
    [date_recorded] => 2016-03-29 04:41:53
    [hide_sitewide] => 0
    [mptt_left] => 0
    [mptt_right] => 0
    [is_spam] => 0
)

There is an action that is called which you can hook into that will be called when this activity takes place. It is xprofile_avatar_uploaded and it passes two parameters, $item_id (user ID), and $type (e.g. crop or camera). This filter is executed after an avatar is uploaded.

Somewhere in your functions, add:

add_action('xprofile_avatar_uploaded', 'callback');

function callback($user_id, $type)
{
    // $user_id uploaded new avatar
}

I found you can also call:

$img = bp_get_activity_avatar(['user_id' => $user_id]);

to get the HTML to display the avatar. They are stored in wp-content/uploads/avatars.

You can also call:

$url = bp_core_fetch_avatar(['item_id' => $user_id, 'html' => false]);

to get just the full URL of the avatar.

drew010
  • 68,777
  • 11
  • 134
  • 162
  • Thanks for the fast reply. The filter is called every time (not only one time after avatar is upload). My idea is know to store the activity id in the user_meta fields after the avatar is successfully changed. Can you please give me the correct hook? – Peter Mar 30 '16 at 01:07
  • Hi, I edited the answer, I believe the `xprofile_avatar_uploaded` action is more accurate. As far as I can tell it is only called after a successful avatar upload. – drew010 Mar 30 '16 at 04:16