BP_Core_User::update_last_activity( int $user_id, string $time )

Set a user’s last_activity value.

Description

Will create a new entry if it does not exist. Otherwise updates the existing entry.

Parameters

$user_id

(int) (Required) ID of the user whose last_activity you are updating.

$time

(string) (Required) MySQL-formatted time string.

Return

(bool) True on success, false on failure.

Source

File: bp-core/classes/class-bp-core-user.php

	public static function update_last_activity( $user_id, $time ) {
		global $wpdb;

		$table_name = buddypress()->members->table_name_last_activity;

		$activity = self::get_last_activity( $user_id );

		if ( ! empty( $activity[ $user_id ] ) ) {
			$updated = $wpdb->update(
				$table_name,

				// Data to update.
				array(
					'date_recorded' => $time,
				),

				// WHERE.
				array(
					'id' => $activity[ $user_id ]['activity_id'],
				),

				// Data sanitization format.
				array(
					'%s',
				),

				// WHERE sanitization format.
				array(
					'%d',
				)
			);

			// Add new date to existing activity entry for caching.
			$activity[ $user_id ]['date_recorded'] = $time;

		} else {
			$updated = $wpdb->insert(
				$table_name,

				// Data.
				array(
					'user_id'       => $user_id,
					'component'     => buddypress()->members->id,
					'type'          => 'last_activity',
					'action'        => '',
					'content'       => '',
					'primary_link'  => '',
					'item_id'       => 0,
					'date_recorded' => $time,
				),

				// Data sanitization format.
				array(
					'%d',
					'%s',
					'%s',
					'%s',
					'%s',
					'%s',
					'%d',
					'%s',
				)
			);

			// Set up activity array for caching.
			// View the foreach loop in the get_last_activity() method for format.
			$activity = array();
			$activity[ $user_id ] = array(
				'user_id'       => $user_id,
				'date_recorded' => $time,
				'activity_id'   => $wpdb->insert_id,
			);
		}

		// Set cache.
		wp_cache_set( $user_id, $activity[ $user_id ], 'bp_last_activity' );

		/**
		 * Fires when a user's last_activity value has been updated.
		 *
		 * @since BuddyPress 2.7.0
		 *
		 * @param int    $user_id ID of the user.
		 * @param string $time    Last activity timestamp, in 'Y-m-d H:i:s' format.
		 */
		do_action( 'bp_core_user_updated_last_activity', $user_id, $time );

		return $updated;
	}

Changelog

Changelog
Version Description
BuddyPress 2.0.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.