[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/block-supports/ -> custom-css.php (source)

   1  <?php
   2  /**
   3   * Custom CSS block support.
   4   *
   5   * @package WordPress
   6   */
   7  
   8  /**
   9   * Render the custom CSS stylesheet and add class name to block as required.
  10   *
  11   * @since 7.0.0
  12   *
  13   * @param array $parsed_block The parsed block.
  14   * @return array The same parsed block with custom CSS class name added if appropriate.
  15   *
  16   * @phpstan-param array{
  17   *     blockName: string|null,
  18   *     attrs: array{
  19   *         className?: string,
  20   *         style?: array{
  21   *             css?: string,
  22   *             ...
  23   *         },
  24   *         ...
  25   *     },
  26   *     ...
  27   * } $parsed_block
  28   * @phpstan-return array{
  29   *     blockName: string|null,
  30   *     attrs: array{
  31   *         className?: string,
  32   *         style?: array{
  33   *             css?: string,
  34   *             ...
  35   *         },
  36   *         ...
  37   *     },
  38   *     ...
  39   * }
  40   */
  41  function wp_render_custom_css_support_styles( $parsed_block ) {
  42      $custom_css = $parsed_block['attrs']['style']['css'] ?? null;
  43      if ( ! is_string( $custom_css ) || '' === trim( $custom_css ) ) {
  44          return $parsed_block;
  45      }
  46  
  47      $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $parsed_block['blockName'] );
  48      if ( ! block_has_support( $block_type, 'customCSS', true ) ) {
  49          return $parsed_block;
  50      }
  51  
  52      // Validate CSS doesn't contain HTML markup (same validation as global styles REST API).
  53      if ( preg_match( '#</?\w+#', $custom_css ) ) {
  54          return $parsed_block;
  55      }
  56  
  57      // Generate a unique class name for this block instance.
  58      $class_name          = wp_unique_id_from_values( $parsed_block, 'wp-custom-css-' );
  59      $existing_class_name = $parsed_block['attrs']['className'] ?? null;
  60      $updated_class_name  = is_string( $existing_class_name )
  61          ? "$existing_class_name $class_name"
  62          : $class_name;
  63  
  64      $parsed_block['attrs']['className'] = $updated_class_name;
  65  
  66      // Process the custom CSS using the same method as global styles.
  67      $selector      = '.' . $class_name;
  68      $processed_css = WP_Theme_JSON::process_blocks_custom_css( $custom_css, $selector );
  69  
  70      if ( ! empty( $processed_css ) ) {
  71          /**
  72           * Reuse one handle so identical custom CSS is enqueued only once via
  73           * {@see wp_unique_id_from_values()}. Explicitly declare the `wp-block-library`
  74           * dependency so `global-styles` is guaranteed to print after it, preventing
  75           * block default styles from unintentionally overriding global styles.
  76           */
  77          $handle = 'wp-block-custom-css';
  78          if ( ! wp_style_is( $handle, 'registered' ) ) {
  79              wp_register_style( $handle, false, array( 'wp-block-library', 'global-styles' ) );
  80          }
  81          $after_styles = wp_styles()->get_data( $handle, 'after' );
  82          if ( ! is_array( $after_styles ) ) {
  83              $after_styles = array();
  84          }
  85          if ( ! in_array( $processed_css, $after_styles, true ) ) {
  86              wp_add_inline_style( $handle, $processed_css );
  87          }
  88      }
  89  
  90      return $parsed_block;
  91  }
  92  
  93  /**
  94   * Enqueues the block custom CSS styles.
  95   *
  96   * @since 7.0.0
  97   */
  98  function wp_enqueue_block_custom_css() {
  99      wp_enqueue_style( 'wp-block-custom-css' );
 100  }
 101  
 102  /**
 103   * Applies the custom CSS class name to the block's rendered HTML.
 104   *
 105   * The class name is generated in {@see wp_render_custom_css_support_styles()}
 106   * and stored in block attributes. This filter adds it to the actual markup.
 107   *
 108   * @since 7.0.0
 109   *
 110   * @param string $block_content Rendered block content.
 111   * @param array  $block         Block object.
 112   * @return string               Filtered block content.
 113   *
 114   * @phpstan-param array{
 115   *     attrs: array{
 116   *         className?: string,
 117   *         ...
 118   *     },
 119   *     ...
 120   * } $block
 121   */
 122  function wp_render_custom_css_class_name( $block_content, $block ) {
 123      $class_name_attr   = $block['attrs']['className'] ?? null;
 124      $class_name_prefix = 'wp-custom-css-';
 125      if ( ! is_string( $class_name_attr ) || ! str_contains( $class_name_attr, $class_name_prefix ) ) {
 126          return $block_content;
 127      }
 128  
 129      // Parse out the 'wp-custom-css-*' class name added by wp_render_custom_css_support_styles().
 130      $matched_class_name = null;
 131      $token_delimiter    = " \t\f\r\n";
 132      $class_token        = strtok( $class_name_attr, $token_delimiter );
 133      while ( false !== $class_token ) {
 134          if ( str_starts_with( $class_token, $class_name_prefix ) ) {
 135              $matched_class_name = $class_token;
 136              break;
 137          }
 138          $class_token = strtok( $token_delimiter );
 139      }
 140      if ( null === $matched_class_name ) {
 141          return $block_content;
 142      }
 143  
 144      $tags = new WP_HTML_Tag_Processor( $block_content );
 145      if ( $tags->next_tag() ) {
 146          $tags->add_class( 'has-custom-css' );
 147          $tags->add_class( $matched_class_name );
 148      }
 149  
 150      return $tags->get_updated_html();
 151  }
 152  
 153  add_filter( 'render_block', 'wp_render_custom_css_class_name', 10, 2 );
 154  add_filter( 'render_block_data', 'wp_render_custom_css_support_styles', 10, 1 );
 155  add_action( 'wp_enqueue_scripts', 'wp_enqueue_block_custom_css', 1 );
 156  
 157  /**
 158   * Registers the style block attribute for block types that support it.
 159   *
 160   * @param WP_Block_Type $block_type Block Type.
 161   */
 162  function wp_register_custom_css_support( $block_type ) {
 163      // Setup attributes and styles within that if needed.
 164      if ( ! $block_type->attributes ) {
 165          $block_type->attributes = array();
 166      }
 167  
 168      // Check for existing style attribute definition e.g. from block.json.
 169      if ( array_key_exists( 'style', $block_type->attributes ) ) {
 170          return;
 171      }
 172  
 173      $has_custom_css_support = block_has_support( $block_type, array( 'customCSS' ), true );
 174  
 175      if ( $has_custom_css_support ) {
 176          $block_type->attributes['style'] = array(
 177              'type' => 'object',
 178          );
 179      }
 180  }
 181  
 182  /**
 183   * Strips custom CSS (`style.css` in attributes) from all blocks in post content.
 184   *
 185   * Uses {@see WP_Block_Parser::next_token()} to scan block tokens and surgically
 186   * replace only the attribute JSON that changed — no parse_blocks() +
 187   * serialize_blocks() round-trip needed.
 188   *
 189   * @since 7.0.0
 190   * @access private
 191   *
 192   * @param string $content Post content to filter, expected to be escaped with slashes.
 193   * @return string Filtered post content with block custom CSS removed.
 194   */
 195  function wp_strip_custom_css_from_blocks( $content ) {
 196      if ( ! has_blocks( $content ) ) {
 197          return $content;
 198      }
 199  
 200      $unslashed = stripslashes( $content );
 201  
 202      $parser           = new WP_Block_Parser();
 203      $parser->document = $unslashed;
 204      $parser->offset   = 0;
 205      $end              = strlen( $unslashed );
 206      $replacements     = array();
 207  
 208      while ( $parser->offset < $end ) {
 209          $next_token = $parser->next_token();
 210  
 211          if ( 'no-more-tokens' === $next_token[0] ) {
 212              break;
 213          }
 214  
 215          list( $token_type, , $attrs, $start_offset, $token_length ) = $next_token;
 216  
 217          $parser->offset = $start_offset + $token_length;
 218  
 219          if ( 'block-opener' !== $token_type && 'void-block' !== $token_type ) {
 220              continue;
 221          }
 222  
 223          if ( ! isset( $attrs['style']['css'] ) ) {
 224              continue;
 225          }
 226  
 227          // Remove css and clean up empty style.
 228          unset( $attrs['style']['css'] );
 229          if ( empty( $attrs['style'] ) ) {
 230              unset( $attrs['style'] );
 231          }
 232  
 233          // Locate the JSON portion within the token.
 234          $token_string   = substr( $unslashed, $start_offset, $token_length );
 235          $json_rel_start = strcspn( $token_string, '{' );
 236          $json_rel_end   = strrpos( $token_string, '}' );
 237  
 238          $json_start  = $start_offset + $json_rel_start;
 239          $json_length = $json_rel_end - $json_rel_start + 1;
 240  
 241          // Re-encode attributes. If attrs is now empty, remove JSON and trailing space.
 242          if ( empty( $attrs ) ) {
 243              // Remove the trailing space after JSON.
 244              $replacements[] = array( $json_start, $json_length + 1, '' );
 245          } else {
 246              $replacements[] = array( $json_start, $json_length, serialize_block_attributes( $attrs ) );
 247          }
 248      }
 249  
 250      if ( empty( $replacements ) ) {
 251          return $content;
 252      }
 253  
 254      // Build the result by splicing replacements into the original string.
 255      $result = '';
 256      $was_at = 0;
 257  
 258      foreach ( $replacements as $replacement ) {
 259          list( $offset, $length, $new_json ) = $replacement;
 260          $result                            .= substr( $unslashed, $was_at, $offset - $was_at ) . $new_json;
 261          $was_at                             = $offset + $length;
 262      }
 263  
 264      if ( $was_at < $end ) {
 265          $result .= substr( $unslashed, $was_at );
 266      }
 267  
 268      return addslashes( $result );
 269  }
 270  
 271  /**
 272   * Adds the filters to strip custom CSS from block content on save.
 273   * Priority of 8 to run before wp_filter_global_styles_post (priority 9) and wp_filter_post_kses (priority 10).
 274   *
 275   * @since 7.0.0
 276   * @access private
 277   */
 278  function wp_custom_css_kses_init_filters() {
 279      add_filter( 'content_save_pre', 'wp_strip_custom_css_from_blocks', 8 );
 280      add_filter( 'content_filtered_save_pre', 'wp_strip_custom_css_from_blocks', 8 );
 281  }
 282  
 283  /**
 284   * Removes the filters that strip custom CSS from block content on save.
 285   * Priority of 8 to run before wp_filter_global_styles_post (priority 9) and wp_filter_post_kses (priority 10).
 286   *
 287   * @since 7.0.0
 288   * @access private
 289   */
 290  function wp_custom_css_remove_filters() {
 291      remove_filter( 'content_save_pre', 'wp_strip_custom_css_from_blocks', 8 );
 292      remove_filter( 'content_filtered_save_pre', 'wp_strip_custom_css_from_blocks', 8 );
 293  }
 294  
 295  /**
 296   * Registers the custom CSS content filters if the user does not have the edit_css capability.
 297   *
 298   * @since 7.0.0
 299   * @access private
 300   */
 301  function wp_custom_css_kses_init() {
 302      wp_custom_css_remove_filters();
 303      if ( ! current_user_can( 'edit_css' ) ) {
 304          wp_custom_css_kses_init_filters();
 305      }
 306  }
 307  
 308  /**
 309   * Initializes custom CSS content filters when imported data should be filtered.
 310   *
 311   * Runs at priority 999 on {@see 'force_filtered_html_on_import'} to ensure it
 312   * fires after general KSES initialization, independently of user capabilities.
 313   * If the input of the filter is true it means we are in an import situation and should
 314   * enable the custom CSS filters, independently of the user capabilities.
 315   *
 316   * @since 7.0.0
 317   * @access private
 318   *
 319   * @param mixed $arg Input argument of the filter.
 320   * @return mixed Input argument of the filter.
 321   */
 322  function wp_custom_css_force_filtered_html_on_import_filter( $arg ) {
 323      if ( $arg ) {
 324          wp_custom_css_kses_init_filters();
 325      }
 326      return $arg;
 327  }
 328  
 329  // Run before wp_filter_global_styles_post (priority 9) and wp_filter_post_kses (priority 10).
 330  add_action( 'init', 'wp_custom_css_kses_init', 20 );
 331  add_action( 'set_current_user', 'wp_custom_css_kses_init' );
 332  add_filter( 'force_filtered_html_on_import', 'wp_custom_css_force_filtered_html_on_import_filter', 999 );
 333  
 334  // Register the block support.
 335  WP_Block_Supports::get_instance()->register(
 336      'custom-css',
 337      array(
 338          'register_attribute' => 'wp_register_custom_css_support',
 339      )
 340  );


Generated : Fri Jul 24 08:20:19 2026 Cross-referenced by PHPXref