add_action('template_redirect', function () { if (!is_user_logged_in()) return; $current_user_id = get_current_user_id(); $current_user = get_userdata($current_user_id); $current_email = $current_user->user_email ?? ''; if (!$current_email) return; $all_keys = []; // Step 1: Collect all mh_network_keys from every site’s wishlist foreach (get_sites(['number' => 0]) as $site) { switch_to_blog($site->blog_id); $sub_user = get_user_by('email', $current_email); if (!$sub_user) { restore_current_blog(); continue; } $wishlist = get_user_meta($sub_user->ID, 'blc_products_wish_list', true); if (!is_array($wishlist) || empty($wishlist['items'])) { restore_current_blog(); continue; } foreach ($wishlist['items'] as $item) { $pid = (int) ($item['id'] ?? 0); if (!$pid) continue; $key = get_post_meta($pid, '_mh_network_key', true); if ($key) { $all_keys[$key] = true; // collect only keys in wishlists } } restore_current_blog(); } // Step 2: Apply union to each site foreach (get_sites(['number' => 0]) as $site) { switch_to_blog($site->blog_id); $sub_user = get_user_by('email', $current_email); if (!$sub_user) { restore_current_blog(); continue; } // Build map only for products in all_keys $key_to_local_id = []; if ($all_keys) { $products = get_posts([ 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', 'meta_query' => [[ 'key' => '_mh_network_key', 'value' => array_keys($all_keys), // only keys we care about 'compare' => 'IN', ]], 'fields' => 'ids', ]); foreach ($products as $pid) { $key = get_post_meta($pid, '_mh_network_key', true); if ($key) { $key_to_local_id[$key] = $pid; } } } $final_ids = []; foreach ($all_keys as $key => $_) { if (isset($key_to_local_id[$key])) { $final_ids[$key_to_local_id[$key]] = true; } } $new_wishlist = [ 'v' => 2, 'items' => array_map(fn($id) => ['id' => $id], array_keys($final_ids)), ]; update_user_meta($sub_user->ID, 'blc_products_wish_list', $new_wishlist); restore_current_blog(); } });