Make WordPress Core


Ignore:
Timestamp:
02/27/2026 07:57:26 PM (4 weeks ago)
Author:
johnjamesjacoby
Message:

Cache API: Introduce fallback for when the wp_cache_switch_to_blog() function is missing.

This commit protects against an edge-case where a persistent object-cache drop-in plugin not including its own wp_cache_switch_to_blog() function would cause non-persistent cache groups to go missing when switching between sites, and includes the following changes:

  • A new wp_cache_switch_to_blog_fallback() function in ms-blogs.php which abstracts duplicated code from switch_to_blog() and restore_current_blog() for easier unit testing
  • A new wpCacheSwitchToBlogFallback.php file with approximately 25 new unit tests
  • Conditionally declares wp_cache_switch_to_blog() in cache-compat.php only if it does not already exist, either via core's cache.php or a drop-in plugin

With this change, WordPress no longer needs to check if the wp_cache_switch_to_blog() function exists (because it always will) so those checks have been removed.

Props ethitter, jeremyfelt, johnjamesjacoby, markjaquith, nacin, ozgursar, r1k0.

Fixes #23290.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/cache-compat.php

    r60697 r61760  
    313313    }
    314314endif;
     315
     316if ( ! function_exists( 'wp_cache_switch_to_blog' ) ) :
     317    /**
     318     * Used when switch_to_blog() and restore_current_blog() are called, but
     319     * only when a persistent object cache drop-in plugin has omitted the
     320     * wp_cache_switch_to_blog() function that was introduced in 3.5.0.
     321     *
     322     * @link https://core.trac.wordpress.org/ticket/23290
     323     *
     324     * @since 7.0.0
     325     *
     326     * @global WP_Object_Cache $wp_object_cache Object cache global instance.
     327     *
     328     * @param int $blog_id Site ID.
     329     */
     330    function wp_cache_switch_to_blog( $blog_id ) {
     331        global $wp_object_cache;
     332
     333        // Attempt to use the drop-in object cache method if it exists.
     334        if ( method_exists( $wp_object_cache, 'switch_to_blog' ) ) {
     335            $wp_object_cache->switch_to_blog( $blog_id );
     336            return;
     337        }
     338
     339        /*
     340         * Perform a fallback blog switch, which will reinitialize the caches
     341         * for the new blog ID.
     342         */
     343        wp_cache_switch_to_blog_fallback( $blog_id );
     344    }
     345endif;
Note: See TracChangeset for help on using the changeset viewer.