From 5b4ee13044a1da9944d38505935be56d6b7beb64 Mon Sep 17 00:00:00 2001
From: Christian Wach <needle@haystack.co.uk>
Date: Tue, 3 Mar 2020 12:04:25 +0000
Subject: [PATCH] Fix synchronisation of Users to Contacts in WordPress
 Multisite

---
 CRM/Utils/System/WordPress.php | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/CRM/Utils/System/WordPress.php b/CRM/Utils/System/WordPress.php
index d1cbaec0872b..6c215d2954f8 100644
--- a/CRM/Utils/System/WordPress.php
+++ b/CRM/Utils/System/WordPress.php
@@ -838,11 +838,13 @@ public function synchronizeUsers() {
     $contactCreated = 0;
     $contactMatching = 0;
 
-    global $wpdb;
-    $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
+    // Previously used the $wpdb global - which means WordPress *must* be bootstrapped.
+    $wpUsers = get_users(array(
+      'blog_id' => get_current_blog_id(),
+      'number' => -1,
+    ));
 
-    foreach ($wpUserIds as $wpUserId) {
-      $wpUserData = get_userdata($wpUserId);
+    foreach ($wpUsers as $wpUserData) {
       $contactCount++;
       if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($wpUserData,
         $wpUserData->$id,
@@ -858,6 +860,9 @@ public function synchronizeUsers() {
       else {
         $contactMatching++;
       }
+      if (is_object($match)) {
+        $match->free();
+      }
     }
 
     return [