Make WordPress Core


Ignore:
Timestamp:
06/04/2024 02:50:24 PM (3 months ago)
Author:
joemcgill
Message:

Editor: Cache global styles for blocks.

This caches the generated CSS from block nodes in merged Theme JSON data to avoid repeated costly operations required to compute style properties for blocks. The generated CSS is saved to a transient that expires every hour.

Props thekt12, spacedmonkey, pereirinha, mukesh27, isabel_brison, oandregal, andrewserong, ramonjd.
Fixes #59595.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/global-styles-and-settings.php

    r58262 r58334  
    308308    $tree        = WP_Theme_JSON_Resolver::get_merged_data();
    309309    $block_nodes = $tree->get_styles_block_nodes();
     310
     311    $can_use_cached = ! wp_is_development_mode( 'theme' );
     312    if ( $can_use_cached ) {
     313        // Hash global settings and block nodes together to optimize performance of key generation.
     314        $hash = md5(
     315            wp_json_encode(
     316                array(
     317                    'global_setting' => wp_get_global_settings(),
     318                    'block_nodes'    => $block_nodes,
     319                )
     320            )
     321        );
     322
     323        $cache_key = "wp_styles_for_blocks:$hash";
     324        $cached    = get_site_transient( $cache_key );
     325        if ( ! is_array( $cached ) ) {
     326            $cached = array();
     327        }
     328    }
     329
     330    $update_cache = false;
     331
    310332    foreach ( $block_nodes as $metadata ) {
    311         $block_css = $tree->get_styles_for_block( $metadata );
     333
     334        if ( $can_use_cached ) {
     335            // Use the block name as the key for cached CSS data. Otherwise, use a hash of the metadata.
     336            $cache_node_key = isset( $metadata['name'] ) ? $metadata['name'] : md5( wp_json_encode( $metadata ) );
     337
     338            if ( isset( $cached[ $cache_node_key ] ) ) {
     339                $block_css = $cached[ $cache_node_key ];
     340            } else {
     341                $block_css                 = $tree->get_styles_for_block( $metadata );
     342                $cached[ $cache_node_key ] = $block_css;
     343                $update_cache              = true;
     344            }
     345        } else {
     346            $block_css = $tree->get_styles_for_block( $metadata );
     347        }
    312348
    313349        if ( ! wp_should_load_separate_core_block_assets() ) {
     
    355391        }
    356392    }
     393
     394    if ( $update_cache ) {
     395        set_site_transient( $cache_key, $cached, HOUR_IN_SECONDS );
     396    }
    357397}
    358398
Note: See TracChangeset for help on using the changeset viewer.