Commit 5798873429f for woocommerce

commit 5798873429f443b234367955234929152af994d7
Author: Rostislav Wolný <1082140+costasovo@users.noreply.github.com>
Date:   Tue Dec 1 11:10:03 2026 +0100

    [Email Editor] Fix multisite emails using the first site's styles (#71500)

    * Fix emails using the first site's styles after switch_to_blog()

    The email editor package keeps its services for the whole PHP process, and
    User_Theme and Site_Style_Sync_Controller cached the email styles post and the
    site theme without checking which site was active. A process that renders
    emails for several sites of a network, for example a loop with
    switch_to_blog(), gave every later site the first site's styles. Core's
    WP_Theme_JSON_Resolver also keeps theme.json data across switch_to_blog(), so
    the controller clears it before loading another site's theme, and the renderer
    clears it again after a render while switched, so the calling site doesn't get
    the other site's data back after restore_current_blog(). A new CI job runs the
    multisite tests, which the single-site jobs skip.

diff --git a/packages/php/email-editor/changelog/wooplug-8342-email-editor-uses-the-first-sites-styles-for b/packages/php/email-editor/changelog/wooplug-8342-email-editor-uses-the-first-sites-styles-for
new file mode 100644
index 00000000000..f2b3a23ad7d
--- /dev/null
+++ b/packages/php/email-editor/changelog/wooplug-8342-email-editor-uses-the-first-sites-styles-for
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Fix emails using the first site's styles when several sites of a network render emails in one request.
diff --git a/packages/php/email-editor/composer.json b/packages/php/email-editor/composer.json
index ccd6ce02ca7..5839c685b18 100644
--- a/packages/php/email-editor/composer.json
+++ b/packages/php/email-editor/composer.json
@@ -46,6 +46,7 @@
 		"env:start": "wp-env start",
 		"test:unit": "wp-env run tests-cli --env-cwd=wp-content/plugins/email-editor ./vendor/bin/phpunit",
 		"test:integration": "wp-env run tests-cli --env-cwd=wp-content/plugins/email-editor ./vendor/bin/phpunit --configuration phpunit-integration.xml.dist",
+		"test:integration:multisite": "wp-env run tests-cli --env-cwd=wp-content/plugins/email-editor env WP_MULTISITE=1 ./vendor/bin/phpunit --configuration phpunit-integration.xml.dist --group ms-required",
 		"phpcs": "phpcs -s -p",
 		"phpcbf": "phpcbf -p"
 	},
diff --git a/packages/php/email-editor/docs/site-style-sync-hooks.md b/packages/php/email-editor/docs/site-style-sync-hooks.md
index 03a9a14f683..efaedeea2f6 100644
--- a/packages/php/email-editor/docs/site-style-sync-hooks.md
+++ b/packages/php/email-editor/docs/site-style-sync-hooks.md
@@ -81,6 +81,8 @@ Filter the site theme data used for email style sync.

 This filter allows overriding the site theme used when syncing global styles for the email editor. Useful for environments where theme data is not directly accessible (e.g., wp.com Atomic and Jetpack sites).

+Note: The email editor keeps the filtered theme in memory for the rest of the request. On multisite, the filter runs again each time the email editor loads styles for a different site (A, B, A runs it three times). Keep the callback fast, or cache its result per site if it does slow work such as a remote request.
+
 ```php
 /**
  * Filter the site theme data used for email style sync.
diff --git a/packages/php/email-editor/package.json b/packages/php/email-editor/package.json
index b784555448c..47f794c7ba4 100644
--- a/packages/php/email-editor/package.json
+++ b/packages/php/email-editor/package.json
@@ -18,6 +18,7 @@
 		"test:unit": "composer run-script test:unit",
 		"test:php:ci": "pnpm test:unit && pnpm test:integration",
 		"test:integration": "composer run-script test:integration",
+		"test:integration:multisite": "composer run-script test:integration:multisite",
 		"test:update-email-snapshots": "wp-env run tests-cli --env-cwd=wp-content/plugins/email-editor env UPDATE_EMAIL_SNAPSHOTS=1 ./vendor/bin/phpunit --configuration phpunit-integration.xml.dist --filter Renderer_Snapshot_Test",
 		"build:composer-package": "bash tasks/build-package.sh"
 	},
@@ -91,6 +92,34 @@
 						"push"
 					]
 				},
+				{
+					"name": "PHP: 8.1 WP: latest (multisite)",
+					"testType": "unit:php",
+					"command": "test:integration:multisite",
+					"changes": [
+						"composer.json",
+						"composer.lock",
+						"**/*.php",
+						"phpunit*.xml.dist",
+						".wp-env.json",
+						"src/**/*.css",
+						"src/**/*.json",
+						"src/**/*.html",
+						"tests/**/*.html",
+						"tests/**/*.txt"
+					],
+					"testEnv": {
+						"start": "env:test",
+						"config": {
+							"phpVersion": "8.1",
+							"wpVersion": "latest"
+						}
+					},
+					"events": [
+						"pull_request",
+						"push"
+					]
+				},
 				{
 					"name": "PHPStan: PHP 7.4",
 					"testType": "static:analysis",
diff --git a/packages/php/email-editor/src/Engine/Renderer/class-renderer.php b/packages/php/email-editor/src/Engine/Renderer/class-renderer.php
index 5b30f153b85..c9ece5ec0d5 100644
--- a/packages/php/email-editor/src/Engine/Renderer/class-renderer.php
+++ b/packages/php/email-editor/src/Engine/Renderer/class-renderer.php
@@ -14,6 +14,7 @@ use Automattic\WooCommerce\EmailEditor\Engine\Renderer\ContentRenderer\Process_M
 use Automattic\WooCommerce\EmailEditor\Engine\Renderer\ContentRenderer\Rendering_Context;
 use Automattic\WooCommerce\EmailEditor\Engine\Templates\Templates;
 use Automattic\WooCommerce\EmailEditor\Engine\Theme_Controller;
+use Automattic\WooCommerce\EmailEditor\Engine\Theme_Json_Cache;
 use Automattic\WooCommerce\EmailEditor\Engine\PersonalizationTags\Personalization_Tags_Registry;
 use Automattic\WooCommerce\EmailEditor\Engine\Personalizer;
 use WP_Style_Engine;
@@ -179,6 +180,9 @@ class Renderer {
 			);
 		} finally {
 			$this->content_renderer->restore_rendering_context( $previous_rendering_context );
+			if ( is_multisite() && ms_is_switched() ) {
+				Theme_Json_Cache::clean_on_next_blog_switch();
+			}
 		}
 	}

diff --git a/packages/php/email-editor/src/Engine/class-site-style-sync-controller.php b/packages/php/email-editor/src/Engine/class-site-style-sync-controller.php
index b50b62eb440..c5016cfef31 100644
--- a/packages/php/email-editor/src/Engine/class-site-style-sync-controller.php
+++ b/packages/php/email-editor/src/Engine/class-site-style-sync-controller.php
@@ -27,6 +27,13 @@ class Site_Style_Sync_Controller {
 	 */
 	private ?WP_Theme_JSON $site_theme = null;

+	/**
+	 * ID of the site the site theme data belongs to.
+	 *
+	 * @var int|null
+	 */
+	private ?int $site_theme_blog_id = null;
+
 	/**
 	 * Base theme data for fallback lookups
 	 *
@@ -142,7 +149,19 @@ class Site_Style_Sync_Controller {
 	 * @return WP_Theme_JSON
 	 */
 	private function get_site_theme(): WP_Theme_JSON {
-		if ( null === $this->site_theme ) {
+		$blog_id = get_current_blog_id();
+		if ( null === $this->site_theme || $blog_id !== $this->site_theme_blog_id ) {
+			$site_changed = null !== $this->site_theme_blog_id && $blog_id !== $this->site_theme_blog_id;
+			if ( is_multisite() ) {
+				if ( $site_changed || ms_is_switched() ) {
+					Theme_Json_Cache::clean();
+				}
+				if ( ms_is_switched() ) {
+					Theme_Json_Cache::clean_on_next_blog_switch();
+				}
+			}
+			$this->site_theme_blog_id = $blog_id;
+
 			// Get only the theme and user customizations (e.g. from site editor).
 			$this->site_theme = new WP_Theme_JSON();
 			$this->site_theme->merge( WP_Theme_JSON_Resolver::get_theme_data() );
diff --git a/packages/php/email-editor/src/Engine/class-theme-json-cache.php b/packages/php/email-editor/src/Engine/class-theme-json-cache.php
new file mode 100644
index 00000000000..fda4fcaad04
--- /dev/null
+++ b/packages/php/email-editor/src/Engine/class-theme-json-cache.php
@@ -0,0 +1,59 @@
+<?php
+/**
+ * This file is part of the WooCommerce Email Editor package.
+ *
+ * @package Automattic\WooCommerce\EmailEditor
+ */
+
+declare(strict_types = 1);
+namespace Automattic\WooCommerce\EmailEditor\Engine;
+
+use WP_Theme_JSON_Resolver;
+
+/**
+ * Clears the theme.json data that WordPress keeps in memory.
+ *
+ * Core's WP_Theme_JSON_Resolver, and the Gutenberg plugin's copy of it, keep resolved theme.json data
+ * for the whole PHP process and don't reset it on switch_to_blog(), so it can belong to another site.
+ *
+ * @internal
+ */
+class Theme_Json_Cache {
+	/**
+	 * Clear the theme.json data kept by core and by the Gutenberg plugin.
+	 */
+	public static function clean(): void {
+		WP_Theme_JSON_Resolver::clean_cached_data();
+		if ( class_exists( 'WP_Theme_JSON_Resolver_Gutenberg' ) ) {
+			\WP_Theme_JSON_Resolver_Gutenberg::clean_cached_data();
+		}
+	}
+
+	/**
+	 * Clear the theme.json data once, when the next switch to another site happens.
+	 *
+	 * Call it when loading a switched site's data, so the site that switched doesn't get that data
+	 * back after restore_current_blog().
+	 */
+	public static function clean_on_next_blog_switch(): void {
+		if ( false === has_action( 'switch_blog', array( self::class, 'clean_on_blog_switch' ) ) ) {
+			add_action( 'switch_blog', array( self::class, 'clean_on_blog_switch' ), 10, 2 );
+		}
+	}
+
+	/**
+	 * Clear the theme.json data when the site changes, then stop listening.
+	 *
+	 * Callback for the `switch_blog` action added by clean_on_next_blog_switch().
+	 *
+	 * @param int|string $new_blog_id  ID of the site switched to.
+	 * @param int|string $prev_blog_id ID of the site switched from.
+	 */
+	public static function clean_on_blog_switch( $new_blog_id, $prev_blog_id ): void {
+		if ( (int) $new_blog_id === (int) $prev_blog_id ) {
+			return;
+		}
+		remove_action( 'switch_blog', array( self::class, 'clean_on_blog_switch' ), 10 );
+		self::clean();
+	}
+}
diff --git a/packages/php/email-editor/src/Engine/class-user-theme.php b/packages/php/email-editor/src/Engine/class-user-theme.php
index 87b3aa03b29..790b5726962 100644
--- a/packages/php/email-editor/src/Engine/class-user-theme.php
+++ b/packages/php/email-editor/src/Engine/class-user-theme.php
@@ -28,6 +28,13 @@ class User_Theme {
 	 */
 	private ?WP_Post $user_theme_post = null;

+	/**
+	 * ID of the site the user theme post belongs to.
+	 *
+	 * @var int|null
+	 */
+	private ?int $user_theme_post_blog_id = null;
+
 	/**
 	 * Getter for user theme.
 	 *
@@ -64,10 +71,12 @@ class User_Theme {
 	 * @throws \Exception If the user theme post cannot be created.
 	 */
 	private function ensure_theme_post(): void {
-		if ( $this->user_theme_post ) {
+		$blog_id = get_current_blog_id();
+		if ( $this->user_theme_post && $blog_id === $this->user_theme_post_blog_id ) {
 			return;
 		}
-		$this->user_theme_post = get_page_by_path( self::USER_THEME_POST_NAME, OBJECT, 'wp_global_styles' );
+		$this->user_theme_post_blog_id = $blog_id;
+		$this->user_theme_post         = get_page_by_path( self::USER_THEME_POST_NAME, OBJECT, 'wp_global_styles' );
 		if ( $this->user_theme_post instanceof WP_Post ) {
 			return;
 		}
diff --git a/packages/php/email-editor/tests/integration/Email_Editor_Integration_Test_Case.php b/packages/php/email-editor/tests/integration/Email_Editor_Integration_Test_Case.php
index 47e852ec0eb..0184f34ea59 100644
--- a/packages/php/email-editor/tests/integration/Email_Editor_Integration_Test_Case.php
+++ b/packages/php/email-editor/tests/integration/Email_Editor_Integration_Test_Case.php
@@ -362,4 +362,71 @@ abstract class Email_Editor_Integration_Test_Case extends \WP_UnitTestCase {
 		// phpcs:enable
 		$this->original_enqueue_registries = null;
 	}
+
+	/**
+	 * Create a site on the network.
+	 *
+	 * @return int Site ID.
+	 */
+	protected function createSite(): int {
+		$site_id = self::factory()->blog->create();
+		$this->assertIsInt( $site_id );
+		return $site_id;
+	}
+
+	/**
+	 * Fill core's cache of the current site's global styles, as rendering a page or an email does.
+	 *
+	 * After core clears its cache, its first read doesn't record the registered blocks, so the next read rebuilds once. After two reads the cache stays.
+	 */
+	protected function fillCoreUserDataCache(): void {
+		WP_Theme_JSON_Resolver::get_user_data();
+		WP_Theme_JSON_Resolver::get_user_data();
+	}
+
+	/**
+	 * Save the email styles (the email editor's Styles panel) on the current site.
+	 *
+	 * @param array $styles Theme.json styles.
+	 */
+	protected function saveEmailStyles( array $styles ): void {
+		$this->insertGlobalStylesPost( 'wp-global-styles-woocommerce-email', $styles );
+	}
+
+	/**
+	 * Save the active theme's global styles (the Site Editor's Styles panel) on the current site.
+	 *
+	 * @param array $styles Theme.json styles.
+	 */
+	protected function saveSiteStyles( array $styles ): void {
+		$post_id = $this->insertGlobalStylesPost( 'wp-global-styles-' . rawurlencode( get_stylesheet() ), $styles );
+		// Core looks the post up by this term, and wp_insert_post() only sets it for users who can assign terms.
+		wp_set_object_terms( $post_id, get_stylesheet(), 'wp_theme' );
+	}
+
+	/**
+	 * Insert a global styles post on the current site.
+	 *
+	 * @param string $post_name Post name.
+	 * @param array  $styles Theme.json styles.
+	 * @return int Post ID.
+	 */
+	private function insertGlobalStylesPost( string $post_name, array $styles ): int {
+		$post_id = wp_insert_post(
+			array(
+				'post_name'    => $post_name,
+				'post_type'    => 'wp_global_styles',
+				'post_status'  => 'publish',
+				'post_content' => (string) wp_json_encode(
+					array(
+						'version'                     => 3,
+						'isGlobalStylesUserThemeJSON' => true,
+						'styles'                      => $styles,
+					)
+				),
+			)
+		);
+		$this->assertIsInt( $post_id );
+		return $post_id;
+	}
 }
diff --git a/packages/php/email-editor/tests/integration/Engine/Fixtures/class-wp-theme-json-resolver-gutenberg.php b/packages/php/email-editor/tests/integration/Engine/Fixtures/class-wp-theme-json-resolver-gutenberg.php
new file mode 100644
index 00000000000..fd2ce7afec1
--- /dev/null
+++ b/packages/php/email-editor/tests/integration/Engine/Fixtures/class-wp-theme-json-resolver-gutenberg.php
@@ -0,0 +1,27 @@
+<?php
+/**
+ * This file is part of the WooCommerce Email Editor package.
+ *
+ * @package Automattic\WooCommerce\EmailEditor
+ */
+
+declare(strict_types = 1);
+
+/**
+ * Stand-in for the Gutenberg plugin's resolver, which the test environment doesn't load.
+ */
+class WP_Theme_JSON_Resolver_Gutenberg {
+	/**
+	 * How many times clean_cached_data() ran.
+	 *
+	 * @var int
+	 */
+	public static int $clean_count = 0;
+
+	/**
+	 * Count the call.
+	 */
+	public static function clean_cached_data(): void {
+		++self::$clean_count;
+	}
+}
diff --git a/packages/php/email-editor/tests/integration/Engine/Renderer/Renderer_Multisite_Test.php b/packages/php/email-editor/tests/integration/Engine/Renderer/Renderer_Multisite_Test.php
new file mode 100644
index 00000000000..4a64487be4f
--- /dev/null
+++ b/packages/php/email-editor/tests/integration/Engine/Renderer/Renderer_Multisite_Test.php
@@ -0,0 +1,126 @@
+<?php
+/**
+ * This file is part of the WooCommerce Email Editor package
+ *
+ * @package Automattic\WooCommerce\EmailEditor
+ */
+
+declare(strict_types = 1);
+namespace Automattic\WooCommerce\EmailEditor\Engine\Renderer;
+
+use Automattic\WooCommerce\EmailEditor\Engine\Email_Editor;
+use WP_Theme_JSON_Resolver;
+
+/**
+ * Integration test for rendering emails of several sites in one request.
+ *
+ * @group ms-required
+ */
+class Renderer_Multisite_Test extends \Email_Editor_Integration_Test_Case {
+	/**
+	 * The renderer.
+	 *
+	 * @var Renderer
+	 */
+	private Renderer $renderer;
+
+	/**
+	 * ID of the second site.
+	 *
+	 * @var int
+	 */
+	private int $other_site_id;
+
+	/**
+	 * Set up both sites with different email and site styles.
+	 */
+	public function setUp(): void {
+		parent::setUp();
+		$this->skipWithoutMultisite();
+		$this->di_container->get( Email_Editor::class )->initialize();
+		$this->renderer = $this->di_container->get( Renderer::class );
+
+		$this->saveEmailStyles( array( 'color' => array( 'background' => '#a1b2c3' ) ) );
+		$this->saveSiteStyles( array( 'color' => array( 'text' => '#1a2b3c' ) ) );
+		$this->other_site_id = $this->createSite();
+		switch_to_blog( $this->other_site_id );
+		$this->saveEmailStyles( array( 'color' => array( 'background' => '#c3b2a1' ) ) );
+		$this->saveSiteStyles( array( 'color' => array( 'text' => '#3c2b1a' ) ) );
+		restore_current_blog();
+	}
+
+	/**
+	 * Test each site's email gets that site's styles when both render in one request.
+	 */
+	public function testItRendersEachSiteWithItsOwnStyles(): void {
+		$this->renderEmail();
+		switch_to_blog( $this->other_site_id );
+		$html = $this->renderEmail();
+		restore_current_blog();
+
+		$this->assertStringContainsString( '#c3b2a1', $html, 'The email background should come from the other site.' );
+		$this->assertStringContainsString( '#3c2b1a', $html, 'The text color should come from the other site.' );
+		$this->assertStringNotContainsString( '#a1b2c3', $html );
+		$this->assertStringNotContainsString( '#1a2b3c', $html );
+	}
+
+	/**
+	 * Test the site that switched gets its own theme data back, even when the other site's data was read after the render.
+	 */
+	public function testItLeavesNoOtherSiteThemeDataInCoreCacheAfterRestore(): void {
+		switch_to_blog( $this->other_site_id );
+		$this->renderEmail();
+		$this->fillCoreUserDataCache();
+		restore_current_blog();
+
+		$user_styles = WP_Theme_JSON_Resolver::get_user_data()->get_raw_data()['styles'] ?? array();
+		$this->assertSame( '#1a2b3c', $user_styles['color']['text'] ?? null, 'The site that switched should get its own site styles back.' );
+	}
+
+	/**
+	 * Test a render on a second visit to the same site leaves none of that site's theme data in core's cache.
+	 *
+	 * On the second visit the controller reuses its cached theme and doesn't schedule the clean-up, so only the renderer does.
+	 */
+	public function testItLeavesNoOtherSiteThemeDataInCoreCacheAfterSecondRenderForSameSite(): void {
+		switch_to_blog( $this->other_site_id );
+		$this->renderEmail();
+		restore_current_blog();
+
+		switch_to_blog( $this->other_site_id );
+		$this->renderEmail();
+		$this->fillCoreUserDataCache();
+		restore_current_blog();
+
+		$user_styles = WP_Theme_JSON_Resolver::get_user_data()->get_raw_data()['styles'] ?? array();
+		$this->assertSame( '#1a2b3c', $user_styles['color']['text'] ?? null, 'The site that switched should get its own site styles back.' );
+	}
+
+	/**
+	 * Test several renders for the same switched site keep core's cache between them.
+	 */
+	public function testItKeepsCoreCacheBetweenRendersForSameSite(): void {
+		switch_to_blog( $this->other_site_id );
+		$this->renderEmail();
+		$this->fillCoreUserDataCache();
+		$user_data_before = WP_Theme_JSON_Resolver::get_user_data();
+		$this->renderEmail();
+		$user_data_after = WP_Theme_JSON_Resolver::get_user_data();
+		restore_current_blog();
+
+		$this->assertSame( $user_data_before, $user_data_after, 'Core should not rebuild its cache for a second render of the same site.' );
+	}
+
+	/**
+	 * Render an email on the current site.
+	 *
+	 * @return string Email HTML.
+	 */
+	private function renderEmail(): string {
+		$post_id = self::factory()->post->create( array( 'post_content' => '<!-- wp:paragraph --><p>Hello!</p><!-- /wp:paragraph -->' ) );
+		$this->assertIsInt( $post_id );
+		$post = get_post( $post_id );
+		$this->assertInstanceOf( \WP_Post::class, $post );
+		return $this->renderer->render( $post, 'Subject', '', 'en' )['html'];
+	}
+}
diff --git a/packages/php/email-editor/tests/integration/Engine/Site_Style_Sync_Controller_Test.php b/packages/php/email-editor/tests/integration/Engine/Site_Style_Sync_Controller_Test.php
index 208586ba821..9cb9e848a8a 100644
--- a/packages/php/email-editor/tests/integration/Engine/Site_Style_Sync_Controller_Test.php
+++ b/packages/php/email-editor/tests/integration/Engine/Site_Style_Sync_Controller_Test.php
@@ -12,6 +12,7 @@ namespace Automattic\WooCommerce\EmailEditor\Tests\Integration\Engine;
 use Automattic\WooCommerce\EmailEditor\Engine\Site_Style_Sync_Controller;
 use Automattic\WooCommerce\EmailEditor\Tests\Integration\Email_Editor_Integration_Test_Case;
 use WP_Theme_JSON;
+use WP_Theme_JSON_Resolver;

 /**
  * Class Site_Style_Sync_Controller_Test
@@ -147,11 +148,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		// Use reflection to set the private site_theme property.
-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -329,10 +326,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -360,11 +354,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		// Use reflection to set the private site_theme property.
-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -397,11 +387,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		// Use reflection to set the private site_theme property.
-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -442,10 +428,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -534,10 +517,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -566,11 +546,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		// Use reflection to set the private site_theme property.
-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -641,10 +617,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -782,10 +755,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -822,10 +792,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -930,10 +897,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -1060,10 +1024,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		// Create a mock theme.
 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -1211,11 +1172,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		);
 		$site_theme      = new WP_Theme_JSON( $site_theme_data );

-		// Use reflection to set the site theme.
-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $site_theme );
+		$this->set_cached_site_theme( $site_theme );

 		$synced_data = $this->controller->sync_site_styles( $base_theme );

@@ -1243,10 +1200,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		);
 		$site_theme      = new WP_Theme_JSON( $site_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $site_theme );
+		$this->set_cached_site_theme( $site_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -1333,10 +1287,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas

 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -1371,10 +1322,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas

 		$mock_theme = new WP_Theme_JSON( $mock_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $mock_theme );
+		$this->set_cached_site_theme( $mock_theme );

 		$synced_data = $this->controller->sync_site_styles();

@@ -1408,10 +1356,7 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		);
 		$site_theme      = new WP_Theme_JSON( $site_theme_data );

-		$reflection          = new \ReflectionClass( $this->controller );
-		$site_theme_property = $reflection->getProperty( 'site_theme' );
-		$site_theme_property->setAccessible( true );
-		$site_theme_property->setValue( $this->controller, $site_theme );
+		$this->set_cached_site_theme( $site_theme );

 		$synced_data = $this->controller->sync_site_styles( $base_theme );

@@ -1484,6 +1429,95 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 		}
 	}

+	/**
+	 * Test the site theme is loaded once while the site stays the same.
+	 */
+	public function test_get_theme_reuses_site_theme_for_same_site(): void {
+		$site_theme_loads = 0;
+		add_filter(
+			'woocommerce_email_editor_site_theme',
+			static function ( $site_theme ) use ( &$site_theme_loads ) {
+				++$site_theme_loads;
+				return $site_theme;
+			}
+		);
+
+		$this->controller->get_theme();
+		$this->controller->get_theme();
+
+		$this->assertSame( 1, $site_theme_loads );
+	}
+
+	/**
+	 * Test the site theme comes from the current site after switch_to_blog().
+	 *
+	 * @group ms-required
+	 */
+	public function test_get_theme_uses_current_site_styles_after_switch_to_blog(): void {
+		$this->skipWithoutMultisite();
+		$this->saveSiteStyles( array( 'color' => array( 'text' => '#1a2b3c' ) ) );
+		$other_site_id = $this->createSite();
+		switch_to_blog( $other_site_id );
+		$this->saveSiteStyles( array( 'color' => array( 'text' => '#3c2b1a' ) ) );
+		restore_current_blog();
+
+		$this->controller->get_theme();
+		switch_to_blog( $other_site_id );
+		$other_site_theme = $this->controller->get_theme();
+		restore_current_blog();
+		// Another switch that doesn't use the email editor leaves the other site's data in core's cache, so get_theme() has to notice the site change itself.
+		switch_to_blog( $other_site_id );
+		$this->fillCoreUserDataCache();
+		restore_current_blog();
+		$main_site_theme = $this->controller->get_theme();
+
+		$this->assertInstanceOf( WP_Theme_JSON::class, $other_site_theme );
+		$this->assertSame( '#3c2b1a', $other_site_theme->get_data()['styles']['color']['text'] ?? null, 'The other site should get its own site styles.' );
+		$this->assertInstanceOf( WP_Theme_JSON::class, $main_site_theme );
+		$this->assertSame( '#1a2b3c', $main_site_theme->get_data()['styles']['color']['text'] ?? null, 'The main site should get its own site styles back after restore_current_blog().' );
+	}
+
+	/**
+	 * Test loading another site's theme leaves none of its data in core's cache after restore_current_blog().
+	 *
+	 * @group ms-required
+	 */
+	public function test_get_theme_while_switched_leaves_no_other_site_data_in_core_after_restore(): void {
+		$this->skipWithoutMultisite();
+		$this->saveSiteStyles( array( 'color' => array( 'text' => '#1a2b3c' ) ) );
+		$other_site_id = $this->createSite();
+		switch_to_blog( $other_site_id );
+		$this->saveSiteStyles( array( 'color' => array( 'text' => '#3c2b1a' ) ) );
+		$this->controller->get_theme();
+		$this->fillCoreUserDataCache();
+		restore_current_blog();
+
+		$user_styles = WP_Theme_JSON_Resolver::get_user_data()->get_raw_data()['styles'] ?? array();
+		$this->assertSame( '#1a2b3c', $user_styles['color']['text'] ?? null, 'The site that switched should get its own site styles back.' );
+	}
+
+	/**
+	 * Test the first site theme load inside switch_to_blog() ignores core's cache of the original site.
+	 *
+	 * @group ms-required
+	 */
+	public function test_get_theme_first_loaded_while_switched_uses_current_site_styles(): void {
+		$this->skipWithoutMultisite();
+		$this->saveSiteStyles( array( 'color' => array( 'text' => '#1a2b3c' ) ) );
+		$other_site_id = $this->createSite();
+		switch_to_blog( $other_site_id );
+		$this->saveSiteStyles( array( 'color' => array( 'text' => '#3c2b1a' ) ) );
+		restore_current_blog();
+		$this->fillCoreUserDataCache();
+
+		switch_to_blog( $other_site_id );
+		$other_site_theme = $this->controller->get_theme();
+		restore_current_blog();
+
+		$this->assertInstanceOf( WP_Theme_JSON::class, $other_site_theme );
+		$this->assertSame( '#3c2b1a', $other_site_theme->get_data()['styles']['color']['text'] ?? null );
+	}
+
 	/**
 	 * Make the controller sync the given theme data as the site theme.
 	 *
@@ -1497,4 +1531,23 @@ class Site_Style_Sync_Controller_Test extends \Email_Editor_Integration_Test_Cas
 			}
 		);
 	}
+
+	/**
+	 * Set the controller's cached site theme, as if it had loaded it for the current site.
+	 *
+	 * @param WP_Theme_JSON $site_theme Site theme.
+	 */
+	private function set_cached_site_theme( WP_Theme_JSON $site_theme ): void {
+		$reflection = new \ReflectionClass( $this->controller );
+		foreach (
+			array(
+				'site_theme'         => $site_theme,
+				'site_theme_blog_id' => get_current_blog_id(),
+			) as $property_name => $value
+		) {
+			$property = $reflection->getProperty( $property_name );
+			$property->setAccessible( true );
+			$property->setValue( $this->controller, $value );
+		}
+	}
 }
diff --git a/packages/php/email-editor/tests/integration/Engine/Theme_Json_Cache_Test.php b/packages/php/email-editor/tests/integration/Engine/Theme_Json_Cache_Test.php
new file mode 100644
index 00000000000..5b852d32906
--- /dev/null
+++ b/packages/php/email-editor/tests/integration/Engine/Theme_Json_Cache_Test.php
@@ -0,0 +1,54 @@
+<?php
+/**
+ * This file is part of the WooCommerce Email Editor package.
+ *
+ * @package Automattic\WooCommerce\EmailEditor
+ */
+
+declare(strict_types = 1);
+namespace Automattic\WooCommerce\EmailEditor\Engine;
+
+/**
+ * Integration test for Theme_Json_Cache class
+ */
+class Theme_Json_Cache_Test extends \Email_Editor_Integration_Test_Case {
+	/**
+	 * Load the stand-in for the Gutenberg plugin's resolver and reset its counter.
+	 */
+	public function setUp(): void {
+		parent::setUp();
+		if ( ! class_exists( 'WP_Theme_JSON_Resolver_Gutenberg' ) ) {
+			require_once __DIR__ . '/Fixtures/class-wp-theme-json-resolver-gutenberg.php';
+		}
+		if ( ! property_exists( 'WP_Theme_JSON_Resolver_Gutenberg', 'clean_count' ) ) {
+			$this->markTestSkipped( 'The real Gutenberg plugin is loaded.' );
+		}
+		\WP_Theme_JSON_Resolver_Gutenberg::$clean_count = 0;
+	}
+
+	/**
+	 * Test it also clears the Gutenberg plugin's resolver.
+	 */
+	public function testItCleansGutenbergResolverToo(): void {
+		Theme_Json_Cache::clean();
+
+		$this->assertSame( 1, \WP_Theme_JSON_Resolver_Gutenberg::$clean_count );
+	}
+
+	/**
+	 * Test it clears once, on the next switch to another site.
+	 */
+	public function testItCleansOnceOnNextSwitchToAnotherSite(): void {
+		$listener = array( Theme_Json_Cache::class, 'clean_on_blog_switch' );
+		Theme_Json_Cache::clean_on_next_blog_switch();
+		Theme_Json_Cache::clean_on_next_blog_switch();
+
+		Theme_Json_Cache::clean_on_blog_switch( 1, 1 );
+		$this->assertSame( 0, \WP_Theme_JSON_Resolver_Gutenberg::$clean_count, 'A switch to the same site should not clear.' );
+		$this->assertNotFalse( has_action( 'switch_blog', $listener ), 'The listener should wait for a switch to another site.' );
+
+		Theme_Json_Cache::clean_on_blog_switch( 2, 1 );
+		$this->assertSame( 1, \WP_Theme_JSON_Resolver_Gutenberg::$clean_count );
+		$this->assertFalse( has_action( 'switch_blog', $listener ), 'The listener should stop after it clears.' );
+	}
+}
diff --git a/packages/php/email-editor/tests/integration/Engine/User_Theme_Test.php b/packages/php/email-editor/tests/integration/Engine/User_Theme_Test.php
index f0a991bf42a..5e9962cb5ad 100644
--- a/packages/php/email-editor/tests/integration/Engine/User_Theme_Test.php
+++ b/packages/php/email-editor/tests/integration/Engine/User_Theme_Test.php
@@ -81,4 +81,27 @@ class User_Theme_Test extends \Email_Editor_Integration_Test_Case {
 		$raw   = $theme->get_raw_data();
 		$this->assertArrayHasKey( 'version', $raw );
 	}
+
+	/**
+	 * Test it loads the email styles of the current site after switch_to_blog().
+	 *
+	 * @group ms-required
+	 */
+	public function testItLoadsEmailStylesOfCurrentSiteAfterSwitchToBlog(): void {
+		$this->skipWithoutMultisite();
+		$this->saveEmailStyles( array( 'color' => array( 'background' => '#a1b2c3' ) ) );
+		$other_site_id = $this->createSite();
+		switch_to_blog( $other_site_id );
+		$this->saveEmailStyles( array( 'color' => array( 'background' => '#c3b2a1' ) ) );
+		restore_current_blog();
+
+		$this->user_theme->get_theme();
+		switch_to_blog( $other_site_id );
+		$other_site_styles = $this->user_theme->get_theme()->get_raw_data()['styles'] ?? array();
+		restore_current_blog();
+		$main_site_styles = $this->user_theme->get_theme()->get_raw_data()['styles'] ?? array();
+
+		$this->assertSame( '#c3b2a1', $other_site_styles['color']['background'] ?? null, 'The other site should get its own email styles.' );
+		$this->assertSame( '#a1b2c3', $main_site_styles['color']['background'] ?? null, 'The main site should get its own email styles back after restore_current_blog().' );
+	}
 }