bp_activity_add_user_favorite( int $activity_id, int $user_id )

Add an activity feed item as a favorite for a user.

Description

Parameters

$activity_id

(Required) ID of the activity item being favorited.

$user_id

(Required) ID of the user favoriting the activity item.

Return

(bool) True on success, false on failure.

Source

File: bp-activity/bp-activity-functions.php

function bp_activity_add_user_favorite( $activity_id, $user_id = 0 ) {

	// Fallback to logged in user if no user_id is passed.
	if ( empty( $user_id ) ) {
		$user_id = bp_loggedin_user_id();
	}

	$my_favs = bp_get_user_meta( $user_id, 'bp_favorite_activities', true );
	if ( empty( $my_favs ) || ! is_array( $my_favs ) ) {
		$my_favs = array();
	}

	// Bail if the user has already favorited this activity item.
	if ( in_array( $activity_id, $my_favs ) ) {
		return false;
	}

	// Add to user's favorites.
	$my_favs[] = $activity_id;

	// Update the total number of users who have favorited this activity.
	$fav_count = bp_activity_get_meta( $activity_id, 'favorite_count' );
	$fav_count = !empty( $fav_count ) ? (int) $fav_count + 1 : 1;

	// Update the users who have favorited this activity.
	$users = bp_activity_get_meta( $activity_id, 'bp_favorite_users', true );
	if ( empty( $users ) || ! is_array( $users ) ) {
		$users = array();
	}
	// Add to activity's favorited users.
	$users[] = $user_id;

	// Update user meta.
	bp_update_user_meta( $user_id, 'bp_favorite_activities', array_unique( $my_favs ) );

	// Update activity meta
	bp_activity_update_meta( $activity_id, 'bp_favorite_users', array_unique( $users ) );

	// Update activity meta counts.
	if ( bp_activity_update_meta( $activity_id, 'favorite_count', $fav_count ) ) {

		/**
		 * Fires if bp_activity_update_meta() for favorite_count is successful and before returning a true value for success.
		 *
		 * @since BuddyPress 1.2.1
		 *
		 * @param int $activity_id ID of the activity item being favorited.
		 * @param int $user_id     ID of the user doing the favoriting.
		 */
		do_action( 'bp_activity_add_user_favorite', $activity_id, $user_id );

		// Success.
		return true;

	// Saving meta was unsuccessful for an unknown reason.
	} else {

		/**
		 * Fires if bp_activity_update_meta() for favorite_count is unsuccessful and before returning a false value for failure.
		 *
		 * @since BuddyPress 1.5.0
		 *
		 * @param int $activity_id ID of the activity item being favorited.
		 * @param int $user_id     ID of the user doing the favoriting.
		 */
		do_action( 'bp_activity_add_user_favorite_fail', $activity_id, $user_id );

		return false;
	}
}

Changelog

Changelog
Version Description
BuddyPress 1.2.0 Introduced.

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.