[ 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   * @since 7.0.0
 161   *
 162   * @param WP_Block_Type $block_type Block Type.
 163   */
 164  function wp_register_custom_css_support( $block_type ) {
 165      // Setup attributes and styles within that if needed.
 166      if ( ! $block_type->attributes ) {
 167          $block_type->attributes = array();
 168      }
 169  
 170      // Check for existing style attribute definition e.g. from block.json.
 171      if ( array_key_exists( 'style', $block_type->attributes ) ) {
 172          return;
 173      }
 174  
 175      $has_custom_css_support = block_has_support( $block_type, array( 'customCSS' ), true );
 176  
 177      if ( $has_custom_css_support ) {
 178          $block_type->attributes['style'] = array(
 179              'type' => 'object',
 180          );
 181      }
 182  }
 183  
 184  /**
 185   * Strips custom CSS (`style.css` in attributes) from all blocks in post content.
 186   *
 187   * Uses {@see WP_Block_Parser::next_token()} to scan block tokens and surgically
 188   * replace only the attribute JSON that changed — no parse_blocks() +
 189   * serialize_blocks() round-trip needed.
 190   *
 191   * @since 7.0.0
 192   * @access private
 193   *
 194   * @param string $content Post content to filter, expected to be escaped with slashes.
 195   * @return string Filtered post content with block custom CSS removed.
 196   */
 197  function wp_strip_custom_css_from_blocks( $content ) {
 198      if ( ! has_blocks( $content ) ) {
 199          return $content;
 200      }
 201  
 202      $unslashed = stripslashes( $content );
 203  
 204      $parser           = new WP_Block_Parser();
 205      $parser->document = $unslashed;
 206      $parser->offset   = 0;
 207      $end              = strlen( $unslashed );
 208      $replacements     = array();
 209  
 210      while ( $parser->offset < $end ) {
 211          $next_token = $parser->next_token();
 212  
 213          if ( 'no-more-tokens' === $next_token[0] ) {
 214              break;
 215          }
 216  
 217          list( $token_type, , $attrs, $start_offset, $token_length ) = $next_token;
 218  
 219          $parser->offset = $start_offset + $token_length;
 220  
 221          if ( 'block-opener' !== $token_type && 'void-block' !== $token_type ) {
 222              continue;
 223          }
 224  
 225          if ( ! isset( $attrs['style']['css'] ) ) {
 226              continue;
 227          }
 228  
 229          // Remove css and clean up empty style.
 230          unset( $attrs['style']['css'] );
 231          if ( empty( $attrs['style'] ) ) {
 232              unset( $attrs['style'] );
 233          }
 234  
 235          // Locate the JSON portion within the token.
 236          $token_string   = substr( $unslashed, $start_offset, $token_length );
 237          $json_rel_start = strcspn( $token_string, '{' );
 238          $json_rel_end   = strrpos( $token_string, '}' );
 239  
 240          $json_start  = $start_offset + $json_rel_start;
 241          $json_length = $json_rel_end - $json_rel_start + 1;
 242  
 243          // Re-encode attributes. If attrs is now empty, remove JSON and trailing space.
 244          if ( empty( $attrs ) ) {
 245              // Remove the trailing space after JSON.
 246              $replacements[] = array( $json_start, $json_length + 1, '' );
 247          } else {
 248              $replacements[] = array( $json_start, $json_length, serialize_block_attributes( $attrs ) );
 249          }
 250      }
 251  
 252      if ( empty( $replacements ) ) {
 253          return $content;
 254      }
 255  
 256      // Build the result by splicing replacements into the original string.
 257      $result = '';
 258      $was_at = 0;
 259  
 260      foreach ( $replacements as $replacement ) {
 261          list( $offset, $length, $new_json ) = $replacement;
 262          $result                            .= substr( $unslashed, $was_at, $offset - $was_at ) . $new_json;
 263          $was_at                             = $offset + $length;
 264      }
 265  
 266      if ( $was_at < $end ) {
 267          $result .= substr( $unslashed, $was_at );
 268      }
 269  
 270      return addslashes( $result );
 271  }
 272  
 273  /**
 274   * Adds the filters to strip custom CSS from block content on save.
 275   * Priority of 8 to run before wp_filter_global_styles_post (priority 9) and wp_filter_post_kses (priority 10).
 276   *
 277   * @since 7.0.0
 278   * @access private
 279   */
 280  function wp_custom_css_kses_init_filters() {
 281      add_filter( 'content_save_pre', 'wp_strip_custom_css_from_blocks', 8 );
 282      add_filter( 'content_filtered_save_pre', 'wp_strip_custom_css_from_blocks', 8 );
 283  }
 284  
 285  /**
 286   * Removes the filters that strip custom CSS from block content on save.
 287   * Priority of 8 to run before wp_filter_global_styles_post (priority 9) and wp_filter_post_kses (priority 10).
 288   *
 289   * @since 7.0.0
 290   * @access private
 291   */
 292  function wp_custom_css_remove_filters() {
 293      remove_filter( 'content_save_pre', 'wp_strip_custom_css_from_blocks', 8 );
 294      remove_filter( 'content_filtered_save_pre', 'wp_strip_custom_css_from_blocks', 8 );
 295  }
 296  
 297  /**
 298   * Registers the custom CSS content filters if the user does not have the edit_css capability.
 299   *
 300   * @since 7.0.0
 301   * @access private
 302   */
 303  function wp_custom_css_kses_init() {
 304      wp_custom_css_remove_filters();
 305      if ( ! current_user_can( 'edit_css' ) ) {
 306          wp_custom_css_kses_init_filters();
 307      }
 308  }
 309  
 310  /**
 311   * Initializes custom CSS content filters when imported data should be filtered.
 312   *
 313   * Runs at priority 999 on {@see 'force_filtered_html_on_import'} to ensure it
 314   * fires after general KSES initialization, independently of user capabilities.
 315   * If the input of the filter is true it means we are in an import situation and should
 316   * enable the custom CSS filters, independently of the user capabilities.
 317   *
 318   * @since 7.0.0
 319   * @access private
 320   *
 321   * @param mixed $arg Input argument of the filter.
 322   * @return mixed Input argument of the filter.
 323   */
 324  function wp_custom_css_force_filtered_html_on_import_filter( $arg ) {
 325      if ( $arg ) {
 326          wp_custom_css_kses_init_filters();
 327      }
 328      return $arg;
 329  }
 330  
 331  // Run before wp_filter_global_styles_post (priority 9) and wp_filter_post_kses (priority 10).
 332  add_action( 'init', 'wp_custom_css_kses_init', 20 );
 333  add_action( 'set_current_user', 'wp_custom_css_kses_init' );
 334  add_filter( 'force_filtered_html_on_import', 'wp_custom_css_force_filtered_html_on_import_filter', 999 );
 335  
 336  // Register the block support.
 337  WP_Block_Supports::get_instance()->register(
 338      'custom-css',
 339      array(
 340          'register_attribute' => 'wp_register_custom_css_support',
 341      )
 342  );


Generated : Tue Sep 22 08:20:31 2026 Cross-referenced by PHPXref