WP_Sync_Post_Meta_Storage::set_awareness_statepublicWP 7.0.0

Sets awareness state for a given room.

Method of the class: WP_Sync_Post_Meta_Storage{}

No Hooks.

Returns

true|false. True on success, false on failure.

Usage

$WP_Sync_Post_Meta_Storage = new WP_Sync_Post_Meta_Storage();
$WP_Sync_Post_Meta_Storage->set_awareness_state( $room, $awareness ): bool;
$room(string) (required)
Room identifier.
$awareness(array) (required)
.

Notes

  • Global. wpdb. $wpdb WordPress database abstraction object.

Changelog

Since 7.0.0 Introduced.

WP_Sync_Post_Meta_Storage::set_awareness_state() code WP 7.0

public function set_awareness_state( string $room, array $awareness ): bool {
	global $wpdb;

	$post_id = $this->get_storage_post_id( $room );
	if ( null === $post_id ) {
		return false;
	}

	// Use direct database operation to avoid cache invalidation performed by
	// post meta functions (`wp_cache_set_posts_last_changed()` and direct
	// `wp_cache_delete()` calls).
	//
	// If two concurrent requests both see no row and both INSERT, the
	// duplicate is harmless: get_awareness_state() reads the latest row
	// (ORDER BY meta_id DESC).
	$meta_id = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s ORDER BY meta_id DESC LIMIT 1",
			$post_id,
			self::AWARENESS_META_KEY
		)
	);

	if ( $meta_id ) {
		return (bool) $wpdb->update(
			$wpdb->postmeta,
			array( 'meta_value' => wp_json_encode( $awareness ) ),
			array( 'meta_id' => $meta_id ),
			array( '%s' ),
			array( '%d' )
		);
	}

	return (bool) $wpdb->insert(
		$wpdb->postmeta,
		array(
			'post_id'    => $post_id,
			'meta_key'   => self::AWARENESS_META_KEY,
			'meta_value' => wp_json_encode( $awareness ),
		),
		array( '%d', '%s', '%s' )
	);
}