wpf_get_user_id

#Overview

There are some cases where WP Fusion needs to convert a CRM contact ID back to a WordPress user ID, for example:

In this case, WP Fusion uses the wpf_get_user_id() function.

On sites with large usermeta tables (10,000,000+ rows), this can be slow.

This filter runs before the database query and returning a non-false value allows you to either disable the lookup entirely, or write your own custom logic to handle the lookup and/or caching the results.

#Parameters

  • $user_id (bool|int): False by default, return a non-false value to bypass the database query
  • $contact_id (string): The contact ID to look up

#Examples

#Completely disable the lookup of user IDs by contact ID

This code will bypass the database query and always return 0 for a contact’s user ID.

add_filter( 'wpf_get_user_id', '__return_zero' );

This is the best solution for performance, but it will have some implications on the functionality of the plugin:

  1. The update and update_tags webhooks will no longer work (the add webhook will still work)
  2. When syncing abandoned cart data, custom fields for existing users that aren’t part of the checkout form will no longer be synced (this should be ok, it’s rare to sync abandoned cart data that’s not part of WooCommerce)
  3. API errors in the logs will no longer be associated with the user ID who triggered the error, they will show as “system”
  4. If you are using Auto Login Links, and a person with a user account on the site visits the auto login link as a guest, this will no longer update the cache of tags on their user account

There may also be other unexpected side effects depending on your connected CRM and active plugins. We will continue to update this list.

#Create a cache of user ID to contact ID pairs

If you are using object caching (Redis, Memcached, etc) you can use wp_cache_set() to add records to the object cache. This can speed up performance considerably on sites with large databases, but it may fill up the cache if you have a lot of users.

function cache_user_ids( $user_id, $contact_id ) {

	$user_id = wp_cache_get( "wpf_user_id_{$contact_id}" );

	if ( false !== $user_id ) {
		return $user_id;
	}

	// Get the user with the query.

	global $wpdb;

	$query = $wpdb->prepare(
		"SELECT user_id
			FROM {$wpdb->usermeta}
			WHERE meta_key = %s
			AND meta_value = %s
			ORDER BY user_id ASC",
		WPF_CONTACT_ID_META_KEY,
		$contact_id
	);

	$user_id = $wpdb->get_var( $query );

	if ( $user_id > 100000000 || is_null( $user_id ) ) {
		// If the user ID is greater than 100 million, it's an auto-login user ID, not a real user.
		$user_id = 0; // no user found.
	}

	wp_cache_add( "wpf_user_id_{$contact_id}", $user_id, '', DAY_IN_SECONDS * 7 );

	return $user_id;

}

add_filter( 'wpf_get_user_id', 'cache_user_ids', 10, 2 );

This example overrides the built in user ID lookup so that all results are cached in the object cache for seven days.

Was this helpful?