[ 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   *
 143   * @param array $types Optional. Types of styles to load.
 144   *                     It accepts as values 'variables', 'presets', 'styles', 'base-layout-styles'.
 145   *                     If empty, it'll load the following:
 146   *                     - for themes without theme.json: 'variables', 'presets', 'base-layout-styles'.
 147   *                     - for themes with theme.json: 'variables', 'presets', 'styles'.
 148   * @return string Stylesheet.
 149   */
 150  function wp_get_global_stylesheet( $types = array() ) {
 151      /*
 152       * Ignore cache when the development mode is set to 'theme', so it doesn't interfere with the theme
 153       * developer's workflow.
 154       */
 155      $can_use_cached = empty( $types ) && ! wp_is_development_mode( 'theme' );
 156  
 157      /*
 158       * By using the 'theme_json' group, this data is marked to be non-persistent across requests.
 159       * @see `wp_cache_add_non_persistent_groups()`.
 160       *
 161       * The rationale for this is to make sure derived data from theme.json
 162       * is always fresh from the potential modifications done via hooks
 163       * that can use dynamic data (modify the stylesheet depending on some option,
 164       * settings depending on user permissions, etc.).
 165       * See some of the existing hooks to modify theme.json behavior:
 166       * @see https://make.wordpress.org/core/2022/10/10/filters-for-theme-json-data/
 167       *
 168       * A different alternative considered was to invalidate the cache upon certain
 169       * events such as options add/update/delete, user meta, etc.
 170       * It was judged not enough, hence this approach.
 171       * @see https://github.com/WordPress/gutenberg/pull/45372
 172       */
 173      $cache_group = 'theme_json';
 174      $cache_key   = 'wp_get_global_stylesheet';
 175      if ( $can_use_cached ) {
 176          $cached = wp_cache_get( $cache_key, $cache_group );
 177          if ( $cached ) {
 178              return $cached;
 179          }
 180      }
 181  
 182      $tree = WP_Theme_JSON_Resolver::get_merged_data();
 183  
 184      $supports_theme_json = wp_theme_has_theme_json();
 185      if ( empty( $types ) && ! $supports_theme_json ) {
 186          $types = array( 'variables', 'presets', 'base-layout-styles' );
 187      } elseif ( empty( $types ) ) {
 188          $types = array( 'variables', 'styles', 'presets' );
 189      }
 190  
 191      /*
 192       * If variables are part of the stylesheet, then add them.
 193       * This is so themes without a theme.json still work as before 5.9:
 194       * they can override the default presets.
 195       * See https://core.trac.wordpress.org/ticket/54782
 196       */
 197      $styles_variables = '';
 198      if ( in_array( 'variables', $types, true ) ) {
 199          /*
 200           * Only use the default, theme, and custom origins. Why?
 201           * Because styles for `blocks` origin are added at a later phase
 202           * (i.e. in the render cycle). Here, only the ones in use are rendered.
 203           * @see wp_add_global_styles_for_blocks
 204           */
 205          $origins          = array( 'default', 'theme', 'custom' );
 206          $styles_variables = $tree->get_stylesheet( array( 'variables' ), $origins );
 207          $types            = array_diff( $types, array( 'variables' ) );
 208      }
 209  
 210      /*
 211       * For the remaining types (presets, styles), we do consider origins:
 212       *
 213       * - themes without theme.json: only the classes for the presets defined by core
 214       * - themes with theme.json: the presets and styles classes, both from core and the theme
 215       */
 216      $styles_rest = '';
 217      if ( ! empty( $types ) ) {
 218          /*
 219           * Only use the default, theme, and custom origins. Why?
 220           * Because styles for `blocks` origin are added at a later phase
 221           * (i.e. in the render cycle). Here, only the ones in use are rendered.
 222           * @see wp_add_global_styles_for_blocks
 223           */
 224          $origins = array( 'default', 'theme', 'custom' );
 225          /*
 226           * If the theme doesn't have theme.json but supports both appearance tools and color palette,
 227           * the 'theme' origin should be included so color palette presets are also output.
 228           */
 229          if ( ! $supports_theme_json && ( current_theme_supports( 'appearance-tools' ) || current_theme_supports( 'border' ) ) && current_theme_supports( 'editor-color-palette' ) ) {
 230              $origins = array( 'default', 'theme' );
 231          } elseif ( ! $supports_theme_json ) {
 232              $origins = array( 'default' );
 233          }
 234          $styles_rest = $tree->get_stylesheet( $types, $origins );
 235      }
 236  
 237      $stylesheet = $styles_variables . $styles_rest;
 238      if ( $can_use_cached ) {
 239          wp_cache_set( $cache_key, $stylesheet, $cache_group );
 240      }
 241  
 242      return $stylesheet;
 243  }
 244  
 245  /**
 246   * Gets the global styles custom CSS from theme.json.
 247   *
 248   * @since 6.2.0
 249   *
 250   * @return string The global styles custom CSS.
 251   */
 252  function wp_get_global_styles_custom_css() {
 253      if ( ! wp_theme_has_theme_json() ) {
 254          return '';
 255      }
 256      /*
 257       * Ignore cache when the development mode is set to 'theme', so it doesn't interfere with the theme
 258       * developer's workflow.
 259       */
 260      $can_use_cached = ! wp_is_development_mode( 'theme' );
 261  
 262      /*
 263       * By using the 'theme_json' group, this data is marked to be non-persistent across requests.
 264       * @see `wp_cache_add_non_persistent_groups()`.
 265       *
 266       * The rationale for this is to make sure derived data from theme.json
 267       * is always fresh from the potential modifications done via hooks
 268       * that can use dynamic data (modify the stylesheet depending on some option,
 269       * settings depending on user permissions, etc.).
 270       * See some of the existing hooks to modify theme.json behavior:
 271       * @see https://make.wordpress.org/core/2022/10/10/filters-for-theme-json-data/
 272       *
 273       * A different alternative considered was to invalidate the cache upon certain
 274       * events such as options add/update/delete, user meta, etc.
 275       * It was judged not enough, hence this approach.
 276       * @see https://github.com/WordPress/gutenberg/pull/45372
 277       */
 278      $cache_key   = 'wp_get_global_styles_custom_css';
 279      $cache_group = 'theme_json';
 280      if ( $can_use_cached ) {
 281          $cached = wp_cache_get( $cache_key, $cache_group );
 282          if ( $cached ) {
 283              return $cached;
 284          }
 285      }
 286  
 287      $tree       = WP_Theme_JSON_Resolver::get_merged_data();
 288      $stylesheet = $tree->get_custom_css();
 289  
 290      if ( $can_use_cached ) {
 291          wp_cache_set( $cache_key, $stylesheet, $cache_group );
 292      }
 293  
 294      return $stylesheet;
 295  }
 296  
 297  /**
 298   * Adds global style rules to the inline style for each block.
 299   *
 300   * @since 6.1.0
 301   *
 302   * @global WP_Styles $wp_styles
 303   */
 304  function wp_add_global_styles_for_blocks() {
 305      global $wp_styles;
 306  
 307      $tree        = WP_Theme_JSON_Resolver::get_merged_data();
 308      $block_nodes = $tree->get_styles_block_nodes();
 309      foreach ( $block_nodes as $metadata ) {
 310          $block_css = $tree->get_styles_for_block( $metadata );
 311  
 312          if ( ! wp_should_load_separate_core_block_assets() ) {
 313              wp_add_inline_style( 'global-styles', $block_css );
 314              continue;
 315          }
 316  
 317          $stylesheet_handle = 'global-styles';
 318  
 319          /*
 320           * When `wp_should_load_separate_core_block_assets()` is true, block styles are
 321           * enqueued for each block on the page in class WP_Block's render function.
 322           * This means there will be a handle in the styles queue for each of those blocks.
 323           * Block-specific global styles should be attached to the global-styles handle, but
 324           * only for blocks on the page, thus we check if the block's handle is in the queue
 325           * before adding the inline style.
 326           * This conditional loading only applies to core blocks.
 327           */
 328          if ( isset( $metadata['name'] ) ) {
 329              if ( str_starts_with( $metadata['name'], 'core/' ) ) {
 330                  $block_name   = str_replace( 'core/', '', $metadata['name'] );
 331                  $block_handle = 'wp-block-' . $block_name;
 332                  if ( in_array( $block_handle, $wp_styles->queue, true ) ) {
 333                      wp_add_inline_style( $stylesheet_handle, $block_css );
 334                  }
 335              } else {
 336                  wp_add_inline_style( $stylesheet_handle, $block_css );
 337              }
 338          }
 339  
 340          // The likes of block element styles from theme.json do not have  $metadata['name'] set.
 341          if ( ! isset( $metadata['name'] ) && ! empty( $metadata['path'] ) ) {
 342              $block_name = wp_get_block_name_from_theme_json_path( $metadata['path'] );
 343              if ( $block_name ) {
 344                  if ( str_starts_with( $block_name, 'core/' ) ) {
 345                      $block_name   = str_replace( 'core/', '', $block_name );
 346                      $block_handle = 'wp-block-' . $block_name;
 347                      if ( in_array( $block_handle, $wp_styles->queue, true ) ) {
 348                          wp_add_inline_style( $stylesheet_handle, $block_css );
 349                      }
 350                  } else {
 351                      wp_add_inline_style( $stylesheet_handle, $block_css );
 352                  }
 353              }
 354          }
 355      }
 356  }
 357  
 358  /**
 359   * Gets the block name from a given theme.json path.
 360   *
 361   * @since 6.3.0
 362   * @access private
 363   *
 364   * @param array $path An array of keys describing the path to a property in theme.json.
 365   * @return string Identified block name, or empty string if none found.
 366   */
 367  function wp_get_block_name_from_theme_json_path( $path ) {
 368      // Block name is expected to be the third item after 'styles' and 'blocks'.
 369      if (
 370          count( $path ) >= 3
 371          && 'styles' === $path[0]
 372          && 'blocks' === $path[1]
 373          && str_contains( $path[2], '/' )
 374      ) {
 375          return $path[2];
 376      }
 377  
 378      /*
 379       * As fallback and for backward compatibility, allow any core block to be
 380       * at any position.
 381       */
 382      $result = array_values(
 383          array_filter(
 384              $path,
 385              static function ( $item ) {
 386                  if ( str_contains( $item, 'core/' ) ) {
 387                      return true;
 388                  }
 389                  return false;
 390              }
 391          )
 392      );
 393      if ( isset( $result[0] ) ) {
 394          return $result[0];
 395      }
 396      return '';
 397  }
 398  
 399  /**
 400   * Checks whether a theme or its parent has a theme.json file.
 401   *
 402   * @since 6.2.0
 403   *
 404   * @return bool Returns true if theme or its parent has a theme.json file, false otherwise.
 405   */
 406  function wp_theme_has_theme_json() {
 407      static $theme_has_support = array();
 408  
 409      $stylesheet = get_stylesheet();
 410  
 411      if (
 412          isset( $theme_has_support[ $stylesheet ] ) &&
 413          /*
 414           * Ignore static cache when the development mode is set to 'theme', to avoid interfering with
 415           * the theme developer's workflow.
 416           */
 417          ! wp_is_development_mode( 'theme' )
 418      ) {
 419          return $theme_has_support[ $stylesheet ];
 420      }
 421  
 422      $stylesheet_directory = get_stylesheet_directory();
 423      $template_directory   = get_template_directory();
 424  
 425      // This is the same as get_theme_file_path(), which isn't available in load-styles.php context
 426      if ( $stylesheet_directory !== $template_directory && file_exists( $stylesheet_directory . '/theme.json' ) ) {
 427          $path = $stylesheet_directory . '/theme.json';
 428      } else {
 429          $path = $template_directory . '/theme.json';
 430      }
 431  
 432      /** This filter is documented in wp-includes/link-template.php */
 433      $path = apply_filters( 'theme_file_path', $path, 'theme.json' );
 434  
 435      $theme_has_support[ $stylesheet ] = file_exists( $path );
 436  
 437      return $theme_has_support[ $stylesheet ];
 438  }
 439  
 440  /**
 441   * Cleans the caches under the theme_json group.
 442   *
 443   * @since 6.2.0
 444   */
 445  function wp_clean_theme_json_cache() {
 446      wp_cache_delete( 'wp_get_global_stylesheet', 'theme_json' );
 447      wp_cache_delete( 'wp_get_global_styles_svg_filters', 'theme_json' );
 448      wp_cache_delete( 'wp_get_global_settings_custom', 'theme_json' );
 449      wp_cache_delete( 'wp_get_global_settings_theme', 'theme_json' );
 450      wp_cache_delete( 'wp_get_global_styles_custom_css', 'theme_json' );
 451      wp_cache_delete( 'wp_get_theme_data_template_parts', 'theme_json' );
 452      WP_Theme_JSON_Resolver::clean_cached_data();
 453  }
 454  
 455  /**
 456   * Returns the current theme's wanted patterns (slugs) to be
 457   * registered from Pattern Directory.
 458   *
 459   * @since 6.3.0
 460   *
 461   * @return string[]
 462   */
 463  function wp_get_theme_directory_pattern_slugs() {
 464      return WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) )->get_patterns();
 465  }
 466  
 467  /**
 468   * Returns the metadata for the custom templates defined by the theme via theme.json.
 469   *
 470   * @since 6.4.0
 471   *
 472   * @return array Associative array of `$template_name => $template_data` pairs,
 473   *               with `$template_data` having "title" and "postTypes" fields.
 474   */
 475  function wp_get_theme_data_custom_templates() {
 476      return WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) )->get_custom_templates();
 477  }
 478  
 479  /**
 480   * Returns the metadata for the template parts defined by the theme.
 481   *
 482   * @since 6.4.0
 483   *
 484   * @return array Associative array of `$part_name => $part_data` pairs,
 485   *               with `$part_data` having "title" and "area" fields.
 486   */
 487  function wp_get_theme_data_template_parts() {
 488      $cache_group    = 'theme_json';
 489      $cache_key      = 'wp_get_theme_data_template_parts';
 490      $can_use_cached = ! wp_is_development_mode( 'theme' );
 491  
 492      $metadata = false;
 493      if ( $can_use_cached ) {
 494          $metadata = wp_cache_get( $cache_key, $cache_group );
 495          if ( false !== $metadata ) {
 496              return $metadata;
 497          }
 498      }
 499  
 500      if ( false === $metadata ) {
 501          $metadata = WP_Theme_JSON_Resolver::get_theme_data( array(), array( 'with_supports' => false ) )->get_template_parts();
 502          if ( $can_use_cached ) {
 503              wp_cache_set( $cache_key, $metadata, $cache_group );
 504          }
 505      }
 506  
 507      return $metadata;
 508  }
 509  
 510  /**
 511   * Determines the CSS selector for the block type and property provided,
 512   * returning it if available.
 513   *
 514   * @since 6.3.0
 515   *
 516   * @param WP_Block_Type $block_type The block's type.
 517   * @param string|array  $target     The desired selector's target, `root` or array path.
 518   * @param boolean       $fallback   Whether to fall back to broader selector.
 519   *
 520   * @return string|null CSS selector or `null` if no selector available.
 521   */
 522  function wp_get_block_css_selector( $block_type, $target = 'root', $fallback = false ) {
 523      if ( empty( $target ) ) {
 524          return null;
 525      }
 526  
 527      $has_selectors = ! empty( $block_type->selectors );
 528  
 529      // Root Selector.
 530  
 531      // Calculated before returning as it can be used as fallback for
 532      // feature selectors later on.
 533      $root_selector = null;
 534  
 535      if ( $has_selectors && isset( $block_type->selectors['root'] ) ) {
 536          // Use the selectors API if available.
 537          $root_selector = $block_type->selectors['root'];
 538      } elseif ( isset( $block_type->supports['__experimentalSelector'] ) && is_string( $block_type->supports['__experimentalSelector'] ) ) {
 539          // Use the old experimental selector supports property if set.
 540          $root_selector = $block_type->supports['__experimentalSelector'];
 541      } else {
 542          // If no root selector found, generate default block class selector.
 543          $block_name    = str_replace( '/', '-', str_replace( 'core/', '', $block_type->name ) );
 544          $root_selector = ".wp-block-{$block_name}";
 545      }
 546  
 547      // Return selector if it's the root target we are looking for.
 548      if ( 'root' === $target ) {
 549          return $root_selector;
 550      }
 551  
 552      // If target is not `root` we have a feature or subfeature as the target.
 553      // If the target is a string convert to an array.
 554      if ( is_string( $target ) ) {
 555          $target = explode( '.', $target );
 556      }
 557  
 558      // Feature Selectors ( May fallback to root selector ).
 559      if ( 1 === count( $target ) ) {
 560          $fallback_selector = $fallback ? $root_selector : null;
 561  
 562          // Prefer the selectors API if available.
 563          if ( $has_selectors ) {
 564              // Look for selector under `feature.root`.
 565              $path             = array( current( $target ), 'root' );
 566              $feature_selector = _wp_array_get( $block_type->selectors, $path, null );
 567  
 568              if ( $feature_selector ) {
 569                  return $feature_selector;
 570              }
 571  
 572              // Check if feature selector is set via shorthand.
 573              $feature_selector = _wp_array_get( $block_type->selectors, $target, null );
 574  
 575              return is_string( $feature_selector ) ? $feature_selector : $fallback_selector;
 576          }
 577  
 578          // Try getting old experimental supports selector value.
 579          $path             = array( current( $target ), '__experimentalSelector' );
 580          $feature_selector = _wp_array_get( $block_type->supports, $path, null );
 581  
 582          // Nothing to work with, provide fallback or null.
 583          if ( null === $feature_selector ) {
 584              return $fallback_selector;
 585          }
 586  
 587          // Scope the feature selector by the block's root selector.
 588          return WP_Theme_JSON::scope_selector( $root_selector, $feature_selector );
 589      }
 590  
 591      // Subfeature selector
 592      // This may fallback either to parent feature or root selector.
 593      $subfeature_selector = null;
 594  
 595      // Use selectors API if available.
 596      if ( $has_selectors ) {
 597          $subfeature_selector = _wp_array_get( $block_type->selectors, $target, null );
 598      }
 599  
 600      // Only return if we have a subfeature selector.
 601      if ( $subfeature_selector ) {
 602          return $subfeature_selector;
 603      }
 604  
 605      // To this point we don't have a subfeature selector. If a fallback
 606      // has been requested, remove subfeature from target path and return
 607      // results of a call for the parent feature's selector.
 608      if ( $fallback ) {
 609          return wp_get_block_css_selector( $block_type, $target[0], $fallback );
 610      }
 611  
 612      return null;
 613  }


Generated : Wed Apr 24 08:20:01 2024 Cross-referenced by PHPXref