[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> global-styles-and-settings.php (source)

   1  <?php
   2  /**
   3   * APIs to interact with global settings & styles.
   4   *
   5   * @package WordPress
   6   */
   7  
   8  /**
   9   * Gets the settings resulting of merging core, theme, and user data.
  10   *
  11   * @since 5.9.0
  12   *
  13   * @param array $path    Path to the specific setting to retrieve. Optional.
  14   *                       If empty, will return all settings.
  15   * @param array $context {
  16   *     Metadata to know where to retrieve the $path from. Optional.
  17   *
  18   *     @type string $block_name Which block to retrieve the settings from.
  19   *                              If empty, it'll return the settings for the global context.
  20   *     @type string $origin     Which origin to take data from.
  21   *                              Valid values are 'all' (core, theme, and user) or 'base' (core and theme).
  22   *                              If empty or unknown, 'all' is used.
  23   * }
  24   * @return mixed The settings array or individual setting value to retrieve.
  25   */
  26  function wp_get_global_settings( $path = array(), $context = array() ) {
  27      if ( ! empty( $context['block_name'] ) ) {
  28          $new_path = array( 'blocks', $context['block_name'] );
  29          foreach ( $path as $subpath ) {
  30              $new_path[] = $subpath;
  31          }
  32          $path = $new_path;
  33      }
  34  
  35      /*
  36       * This is the default value when no origin is provided or when it is 'all'.
  37       *
  38       * The $origin is used as part of the cache key. Changes here need to account
  39       * for clearing the cache appropriately.
  40       */
  41      $origin = 'custom';
  42      if (
  43          ! wp_theme_has_theme_json() ||
  44          ( isset( $context['origin'] ) && 'base' === $context['origin'] )
  45      ) {
  46          $origin = 'theme';
  47      }
  48  
  49      /*
  50       * By using the 'theme_json' group, this data is marked to be non-persistent across requests.
  51       * See `wp_cache_add_non_persistent_groups` in src/wp-includes/load.php and other places.
  52       *
  53       * The rationale for this is to make sure derived data from theme.json
  54       * is always fresh from the potential modifications done via hooks
  55       * that can use dynamic data (modify the stylesheet depending on some option,
  56       * settings depending on user permissions, etc.).
  57       * See some of the existing hooks to modify theme.json behavior:
  58       * https://make.wordpress.org/core/2022/10/10/filters-for-theme-json-data/
  59       *
  60       * A different alternative considered was to invalidate the cache upon certain
  61       * events such as options add/update/delete, user meta, etc.
  62       * It was judged not enough, hence this approach.
  63       * See https://github.com/WordPress/gutenberg/pull/45372
  64       */
  65      $cache_group = 'theme_json';
  66      $cache_key   = 'wp_get_global_settings_' . $origin;
  67  
  68      /*
  69       * Ignore cache when the development mode is set to 'theme', so it doesn't interfere with the theme
  70       * developer's workflow.
  71       */
  72      $can_use_cached = ! wp_is_development_mode( 'theme' );
  73  
  74      $settings = false;
  75      if ( $can_use_cached ) {
  76          $settings = wp_cache_get( $cache_key, $cache_group );
  77      }
  78  
  79      if ( false === $settings ) {
  80          $settings = WP_Theme_JSON_Resolver::get_merged_data( $origin )->get_settings();
  81          if ( $can_use_cached ) {
  82              wp_cache_set( $cache_key, $settings, $cache_group );
  83          }
  84      }
  85  
  86      return _wp_array_get( $settings, $path, $settings );
  87  }
  88  
  89  /**
  90   * Gets the styles resulting of merging core, theme, and user data.
  91   *
  92   * @since 5.9.0
  93   * @since 6.3.0 the internal link format "var:preset|color|secondary" is resolved
  94   *              to "var(--wp--preset--font-size--small)" so consumers don't have to.
  95   * @since 6.3.0 `transforms` is now usable in the `context` parameter. In case [`transforms`]['resolve_variables']
  96   *              is defined, variables are resolved to their value in the styles.
  97   *
  98   * @param array $path    Path to the specific style to retrieve. Optional.
  99   *                       If empty, will return all styles.
 100   * @param array $context {
 101   *     Metadata to know where to retrieve the $path from. Optional.
 102   *
 103   *     @type string $block_name Which block to retrieve the styles from.
 104   *                              If empty, it'll return the styles for the global context.
 105   *     @type string $origin     Which origin to take data from.
 106   *                              Valid values are 'all' (core, theme, and user) or 'base' (core and theme).
 107   *                              If empty or unknown, 'all' is used.
 108   *     @type array $transforms Which transformation(s) to apply.
 109   *                              Valid value is array( 'resolve-variables' ).
 110   *                              If defined, variables are resolved to their value in the styles.
 111   * }
 112   * @return mixed The styles array or individual style value to retrieve.
 113   */
 114  function wp_get_global_styles( $path = array(), $context = array() ) {
 115      if ( ! empty( $context['block_name'] ) ) {
 116          $path = array_merge( array( 'blocks', $context['block_name'] ), $path );
 117      }
 118  
 119      $origin = 'custom';
 120      if ( isset( $context['origin'] ) && 'base' === $context['origin'] ) {
 121          $origin = 'theme';
 122      }
 123  
 124      $resolve_variables = isset( $context['transforms'] )
 125      && is_array( $context['transforms'] )
 126      && in_array( 'resolve-variables', $context['transforms'], true );
 127  
 128      $merged_data = WP_Theme_JSON_Resolver::get_merged_data( $origin );
 129      if ( $resolve_variables ) {
 130          $merged_data = WP_Theme_JSON::resolve_variables( $merged_data );
 131      }
 132      $styles = $merged_data->get_raw_data()['styles'];
 133      return _wp_array_get( $styles, $path, $styles );
 134  }
 135  
 136  
 137  /**
 138   * Returns the stylesheet resulting of merging core, theme, and user data.
 139   *
 140   * @since 5.9.0
 141   * @since 6.1.0 Added 'base-layout-styles' support.
 142   * @since 6.6.0 Resolves relative paths in theme.json styles to theme absolute paths.
 143   *
 144   * @param array $types Optional. Types of styles to load.
 145   *                     See {@see 'WP_Theme_JSON::get_stylesheet'} for all valid types.
 146   *                     If empty, it'll load the following:
 147   *                     - for themes without theme.json: 'variables', 'presets', 'base-layout-styles'.
 148   *                     - for themes with theme.json: 'variables', 'presets', 'styles'.
 149   * @return string Stylesheet.
 150   */
 151  function wp_get_global_stylesheet( $types = array() ) {
 152      /*
 153       * Ignore cache when the development mode is set to 'theme', so it doesn't interfere with the theme
 154       * developer's workflow.
 155       */
 156      $can_use_cached = empty( $types ) && ! wp_is_development_mode( 'theme' );
 157  
 158      /*
 159       * By using the 'theme_json' group, this data is marked to be non-persistent across requests.
 160       * @see `wp_cache_add_non_persistent_groups()`.
 161       *
 162       * The rationale for this is to make sure derived data from theme.json
 163       * is always fresh from the potential modifications done via hooks
 164       * that can use dynamic data (modify the stylesheet depending on some option,
 165       * settings depending on user permissions, etc.).
 166       * See some of the existing hooks to modify theme.json behavior:
 167       * @see https://make.wordpress.org/core/2022/10/10/filters-for-theme-json-data/
 168       *
 169       * A different alternative considered was to invalidate the cache upon certain
 170       * events such as options add/update/delete, user meta, etc.
 171       * It was judged not enough, hence this approach.
 172       * @see https://github.com/WordPress/gutenberg/pull/45372
 173       */
 174      $cache_group = 'theme_json';
 175      $cache_key   = 'wp_get_global_stylesheet';
 176      if ( $can_use_cached ) {
 177          $cached = wp_cache_get( $cache_key, $cache_group );
 178          if ( $cached ) {
 179              return $cached;
 180          }
 181      }
 182  
 183      $tree                = WP_Theme_JSON_Resolver::resolve_theme_file_uris( WP_Theme_JSON_Resolver::get_merged_data() );
 184      $supports_theme_json = wp_theme_has_theme_json();
 185  
 186      if ( empty( $types ) && ! $supports_theme_json ) {
 187          $types = array( 'variables', 'presets', 'base-layout-styles' );
 188      } elseif ( empty( $types ) ) {
 189          $types = array( 'variables', 'styles', 'presets' );
 190      }
 191  
 192      /*
 193       * If variables are part of the stylesheet, then add them.
 194       * This is so themes without a theme.json still work as before 5.9:
 195       * they can override the default presets.
 196       * See https://core.trac.wordpress.org/ticket/54782
 197       */
 198      $styles_variables = '';
 199      if ( in_array( 'variables', $types, true ) ) {
 200          /*
 201           * Only use the default, theme, and custom origins. Why?
 202           * Because styles for `blocks` origin are added at a later phase
 203           * (i.e. in the render cycle). Here, only the ones in use are rendered.
 204           * @see wp_add_global_styles_for_blocks
 205           */
 206          $origins          = array( 'default', 'theme', 'custom' );
 207          $styles_variables = $tree->get_stylesheet( array( 'variables' ), $origins );
 208          $types            = array_diff( $types, array( 'variables' ) );
 209      }
 210  
 211      /*
 212       * For the remaining types (presets, styles), we do consider origins:
 213       *
 214       * - themes without theme.json: only the classes for the presets defined by core
 215       * - themes with theme.json: the presets and styles classes, both from core and the theme
 216       */
 217      $styles_rest = '';
 218      if ( ! empty( $types ) ) {
 219          /*
 220           * Only use the default, theme, and custom origins. Why?
 221           * Because styles for `blocks` origin are added at a later phase
 222           * (i.e. in the render cycle). Here, only the ones in use are rendered.
 223           * @see wp_add_global_styles_for_blocks
 224           */
 225          $origins = array( 'default', 'theme', 'custom' );
 226          /*
 227           * If the theme doesn't have theme.json but supports both appearance tools and color palette,
 228           * the 'theme' origin should be included so color palette presets are also output.
 229           */
 230          if ( ! $supports_theme_json && ( current_theme_supports( 'appearance-tools' ) || current_theme_supports( 'border' ) ) && current_theme_supports( 'editor-color-palette' ) ) {
 231              $origins = array( 'default', 'theme' );
 232          } elseif ( ! $supports_theme_json ) {
 233              $origins = array( 'default' );
 234          }
 235          $styles_rest = $tree->get_stylesheet( $types, $origins );
 236      }
 237  
 238      $stylesheet = $styles_variables . $styles_rest;
 239      if ( $can_use_cached ) {
 240          wp_cache_set( $cache_key, $stylesheet, $cache_group );
 241      }
 242  
 243      return $stylesheet;
 244  }
 245  
 246  /**
 247   * Adds global style rules to the inline style for each block.
 248   *
 249   * @since 6.1.0
 250   * @since 6.7.0 Resolve relative paths in block styles.
 251   *
 252   * @global WP_Styles $wp_styles
 253   */
 254  function wp_add_global_styles_for_blocks() {
 255      global $wp_styles;
 256  
 257      $tree        = WP_Theme_JSON_Resolver::get_merged_data();
 258      $tree        = WP_Theme_JSON_Resolver::resolve_theme_file_uris( $tree );
 259      $block_nodes = $tree->get_styles_block_nodes();
 260  
 261      $can_use_cached = ! wp_is_development_mode( 'theme' );
 262      $update_cache   = false;
 263  
 264      if ( $can_use_cached ) {
 265          // Hash the merged WP_Theme_JSON data to bust cache on settings or styles change.
 266          $cache_hash = md5( wp_json_encode( $tree->get_raw_data() ) );
 267          $cache_key  = 'wp_styles_for_blocks';
 268          $cached     = get_transient( $cache_key );
 269  
 270          // Reset the cached data if there is no value or if the hash has changed.
 271          if ( ! is_array( $cached ) || $cached['hash'] !== $cache_hash ) {
 272              $cached = array(
 273                  'hash'   => $cache_hash,
 274                  'blocks' => array(),
 275              );
 276  
 277              // Update the cache if the hash has changed.
 278              $update_cache = true;
 279          }
 280      }
 281  
 282      foreach ( $block_nodes as $metadata ) {
 283  
 284          if ( $can_use_cached ) {
 285              // Use the block name as the key for cached CSS data. Otherwise, use a hash of the metadata.
 286              $cache_node_key = isset( $metadata['name'] ) ? $metadata['name'] : md5( wp_json_encode( $metadata ) );
 287  
 288              if ( isset( $cached['blocks'][ $cache_node_key ] ) ) {
 289                  $block_css = $cached['blocks'][ $cache_node_key ];
 290              } else {
 291                  $block_css                           = $tree->get_styles_for_block( $metadata );
 292                  $cached['blocks'][ $cache_node_key ] = $block_css;
 293  
 294                  // Update the cache if the cache contents have changed.
 295                  $update_cache = true;
 296              }
 297          } else {
 298              $block_css = $tree->get_styles_for_block( $metadata );
 299          }
 300  
 301          if ( ! wp_should_load_separate_core_block_assets() ) {
 302              wp_add_inline_style( 'global-styles', $block_css );
 303              continue;
 304          }
 305  
 306          $stylesheet_handle = 'global-styles';
 307  
 308          /*
 309           * When `wp_should_load_separate_core_block_assets()` is true, block styles are
 310           * enqueued for each block on the page in class WP_Block's render function.
 311           * This means there will be a handle in the styles queue for each of those blocks.
 312           * Block-specific global styles should be attached to the global-styles handle, but
 313           * only for blocks on the page, thus we check if the block's handle is in the queue
 314           * before adding the inline style.
 315           * This conditional loading only applies to core blocks.
 316           */
 317          if ( isset( $metadata['name'] ) ) {
 318              if ( str_starts_with( $metadata['name'], 'core/' ) ) {
 319                  $block_name   = str_replace( 'core/', '', $metadata['name'] );
 320                  $block_handle = 'wp-block-' . $block_name;
 321                  if ( in_array( $block_handle, $wp_styles->queue, true ) ) {
 322                      wp_add_inline_style( $stylesheet_handle, $block_css );
 323                  }
 324              } else {
 325                  wp_add_inline_style( $stylesheet_handle, $block_css );
 326              }
 327          }
 328  
 329          // The likes of block element styles from theme.json do not have  $metadata['name'] set.
 330          if ( ! isset( $metadata['name'] ) && ! empty( $metadata['path'] ) ) {
 331              $block_name = wp_get_block_name_from_theme_json_path( $metadata['path'] );
 332              if ( $block_name ) {
 333                  if ( str_starts_with( $block_name, 'core/' ) ) {
 334                      $block_name   = str_replace( 'core/', '', $block_name );
 335                      $block_handle = 'wp-block-' . $block_name;
 336                      if ( in_array( $block_handle, $wp_styles->queue, true ) ) {
 337                          wp_add_inline_style( $stylesheet_handle, $block_css );
 338                      }
 339                  } else {
 340                      wp_add_inline_style( $stylesheet_handle, $block_css );
 341                  }
 342              }
 343          }
 344      }
 345  
 346      if ( $update_cache ) {
 347          set_transient( $cache_key, $cached );
 348      }
 349  }
 350  
 351  /**
 352   * Gets the block name from a given theme.json path.
 353   *
 354   * @since 6.3.0
 355   * @access private
 356   *
 357   * @param array $path An array of keys describing the path to a property in theme.json.
 358   * @return string Identified block name, or empty string if none found.
 359   */
 360  function wp_get_block_name_from_theme_json_path( $path ) {
 361      // Block name is expected to be the third item after 'styles' and 'blocks'.
 362      if (
 363          count( $path ) >= 3
 364          && 'styles' === $path[0]
 365          && 'blocks' === $path[1]
 366          && str_contains( $path[2], '/' )
 367      ) {
 368          return $path[2];
 369      }
 370  
 371      /*
 372       * As fallback and for backward compatibility, allow any core block to be
 373       * at any position.
 374       */
 375      $result = array_values(
 376          array_filter(
 377              $path,
 378              static function ( $item ) {
 379                  if ( str_contains( $item, 'core/' ) ) {
 380                      return true;
 381                  }
 382                  return false;
 383              }
 384          )
 385      );
 386      if ( isset( $result[0] ) ) {
 387          return $result[0];
 388      }
 389      return '';
 390  }
 391  
 392  /**
 393   * Checks whether a theme or its parent has a theme.json file.
 394   *
 395   * @since 6.2.0
 396   *
 397   * @return bool Returns true if theme or its parent has a theme.json file, false otherwise.
 398   */
 399  function wp_theme_has_theme_json() {
 400      static $theme_has_support = array();
 401  
 402      $stylesheet = get_stylesheet();
 403  
 404      if (
 405          isset( $theme_has_support[ $stylesheet ] ) &&
 406          /*
 407           * Ignore static cache when the development mode is set to 'theme', to avoid interfering with
 408           * the theme developer's workflow.
 409           */
 410          ! wp_is_development_mode( 'theme' )
 411      ) {
 412          return $theme_has_support[ $stylesheet ];
 413      }
 414  
 415      $stylesheet_directory = get_stylesheet_directory();
 416      $template_directory   = get_template_directory();
 417  
 418      // This is the same as get_theme_file_path(), which isn't available in load-styles.php context
 419      if ( $stylesheet_directory !== $template_directory && file_exists( $stylesheet_directory . '/theme.json' ) ) {
 420          $path = $stylesheet_directory . '/theme.json';
 421      } else {
 422          $path = $template_directory . '/theme.json';
 423      }
 424  
 425      /** This filter is documented in wp-includes/link-template.php */
 426      $path = apply_filters( 'theme_file_path', $path, 'theme.json' );
 427  
 428      $theme_has_support[ $stylesheet ] = file_exists( $path );
 429  
 430      return $theme_has_support[ $stylesheet ];
 431  }
 432  
 433  /**
 434   * Cleans the caches under the theme_json group.
 435   *
 436   * @since 6.2.0
 437   */
 438  function wp_clean_theme_json_cache() {
 439      wp_cache_delete( 'wp_get_global_stylesheet', 'theme_json' );
 440      wp_cache_delete( 'wp_get_global_styles_svg_filters', 'theme_json' );
 441      wp_cache_delete( 'wp_get_global_settings_custom', 'theme_json' );
 442      wp_cache_delete( 'wp_get_global_settings_theme', 'theme_json' );
 443      wp_cache_delete( 'wp_get_global_styles_custom_css', 'theme_json' );
 444      wp_cache_delete( 'wp_get_theme_data_template_parts', 'theme_json' );
 445      WP_Theme_JSON_Resolver::clean_cached_data();
 446  }
 447  
 448  /**
 449   * Returns the current theme's wanted patterns (slugs) to be
 450   * registered from Pattern Directory.
 451   *
 452   * @since 6.3.0
 453   *
 454   * @return string[]
 455   */
 456  function wp_get_theme_directory_pattern_slugs() {
 457      return WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) )->get_patterns();
 458  }
 459  
 460  /**
 461   * Returns the metadata for the custom templates defined by the theme via theme.json.
 462   *
 463   * @since 6.4.0
 464   *
 465   * @return array Associative array of `$template_name => $template_data` pairs,
 466   *               with `$template_data` having "title" and "postTypes" fields.
 467   */
 468  function wp_get_theme_data_custom_templates() {
 469      return WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) )->get_custom_templates();
 470  }
 471  
 472  /**
 473   * Returns the metadata for the template parts defined by the theme.
 474   *
 475   * @since 6.4.0
 476   *
 477   * @return array Associative array of `$part_name => $part_data` pairs,
 478   *               with `$part_data` having "title" and "area" fields.
 479   */
 480  function wp_get_theme_data_template_parts() {
 481      $cache_group    = 'theme_json';
 482      $cache_key      = 'wp_get_theme_data_template_parts';
 483      $can_use_cached = ! wp_is_development_mode( 'theme' );
 484  
 485      $metadata = false;
 486      if ( $can_use_cached ) {
 487          $metadata = wp_cache_get( $cache_key, $cache_group );
 488          if ( false !== $metadata ) {
 489              return $metadata;
 490          }
 491      }
 492  
 493      if ( false === $metadata ) {
 494          $metadata = WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) )->get_template_parts();
 495          if ( $can_use_cached ) {
 496              wp_cache_set( $cache_key, $metadata, $cache_group );
 497          }
 498      }
 499  
 500      return $metadata;
 501  }
 502  
 503  /**
 504   * Determines the CSS selector for the block type and property provided,
 505   * returning it if available.
 506   *
 507   * @since 6.3.0
 508   *
 509   * @param WP_Block_Type $block_type The block's type.
 510   * @param string|array  $target     The desired selector's target, `root` or array path.
 511   * @param boolean       $fallback   Whether to fall back to broader selector.
 512   *
 513   * @return string|null CSS selector or `null` if no selector available.
 514   */
 515  function wp_get_block_css_selector( $block_type, $target = 'root', $fallback = false ) {
 516      if ( empty( $target ) ) {
 517          return null;
 518      }
 519  
 520      $has_selectors = ! empty( $block_type->selectors );
 521  
 522      // Root Selector.
 523  
 524      // Calculated before returning as it can be used as fallback for
 525      // feature selectors later on.
 526      $root_selector = null;
 527  
 528      if ( $has_selectors && isset( $block_type->selectors['root'] ) ) {
 529          // Use the selectors API if available.
 530          $root_selector = $block_type->selectors['root'];
 531      } elseif ( isset( $block_type->supports['__experimentalSelector'] ) && is_string( $block_type->supports['__experimentalSelector'] ) ) {
 532          // Use the old experimental selector supports property if set.
 533          $root_selector = $block_type->supports['__experimentalSelector'];
 534      } else {
 535          // If no root selector found, generate default block class selector.
 536          $block_name    = str_replace( '/', '-', str_replace( 'core/', '', $block_type->name ) );
 537          $root_selector = ".wp-block-{$block_name}";
 538      }
 539  
 540      // Return selector if it's the root target we are looking for.
 541      if ( 'root' === $target ) {
 542          return $root_selector;
 543      }
 544  
 545      // If target is not `root` we have a feature or subfeature as the target.
 546      // If the target is a string convert to an array.
 547      if ( is_string( $target ) ) {
 548          $target = explode( '.', $target );
 549      }
 550  
 551      // Feature Selectors ( May fallback to root selector ).
 552      if ( 1 === count( $target ) ) {
 553          $fallback_selector = $fallback ? $root_selector : null;
 554  
 555          // Prefer the selectors API if available.
 556          if ( $has_selectors ) {
 557              // Look for selector under `feature.root`.
 558              $path             = array( current( $target ), 'root' );
 559              $feature_selector = _wp_array_get( $block_type->selectors, $path, null );
 560  
 561              if ( $feature_selector ) {
 562                  return $feature_selector;
 563              }
 564  
 565              // Check if feature selector is set via shorthand.
 566              $feature_selector = _wp_array_get( $block_type->selectors, $target, null );
 567  
 568              return is_string( $feature_selector ) ? $feature_selector : $fallback_selector;
 569          }
 570  
 571          // Try getting old experimental supports selector value.
 572          $path             = array( current( $target ), '__experimentalSelector' );
 573          $feature_selector = _wp_array_get( $block_type->supports, $path, null );
 574  
 575          // Nothing to work with, provide fallback or null.
 576          if ( null === $feature_selector ) {
 577              return $fallback_selector;
 578          }
 579  
 580          // Scope the feature selector by the block's root selector.
 581          return WP_Theme_JSON::scope_selector( $root_selector, $feature_selector );
 582      }
 583  
 584      // Subfeature selector
 585      // This may fallback either to parent feature or root selector.
 586      $subfeature_selector = null;
 587  
 588      // Use selectors API if available.
 589      if ( $has_selectors ) {
 590          $subfeature_selector = _wp_array_get( $block_type->selectors, $target, null );
 591      }
 592  
 593      // Only return if we have a subfeature selector.
 594      if ( $subfeature_selector ) {
 595          return $subfeature_selector;
 596      }
 597  
 598      // To this point we don't have a subfeature selector. If a fallback
 599      // has been requested, remove subfeature from target path and return
 600      // results of a call for the parent feature's selector.
 601      if ( $fallback ) {
 602          return wp_get_block_css_selector( $block_type, $target[0], $fallback );
 603      }
 604  
 605      return null;
 606  }


Generated : Sat Dec 21 08:20:01 2024 Cross-referenced by PHPXref