Keine Beschreibung

elements.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Elements styles block support.
  4. *
  5. * @package WordPress
  6. * @since 5.8.0
  7. */
  8. /**
  9. * Render the elements stylesheet.
  10. *
  11. * @since 5.8.0
  12. * @access private
  13. *
  14. * @param string $block_content Rendered block content.
  15. * @param array $block Block object.
  16. * @return string Filtered block content.
  17. */
  18. function wp_render_elements_support( $block_content, $block ) {
  19. $link_color = null;
  20. if ( ! empty( $block['attrs'] ) ) {
  21. $link_color = _wp_array_get( $block['attrs'], array( 'style', 'elements', 'link', 'color', 'text' ), null );
  22. }
  23. /*
  24. * For now we only care about link color.
  25. * This code in the future when we have a public API
  26. * should take advantage of WP_Theme_JSON::compute_style_properties
  27. * and work for any element and style.
  28. */
  29. if ( null === $link_color ) {
  30. return $block_content;
  31. }
  32. $class_name = 'wp-elements-' . uniqid();
  33. if ( strpos( $link_color, 'var:preset|color|' ) !== false ) {
  34. // Get the name from the string and add proper styles.
  35. $index_to_splice = strrpos( $link_color, '|' ) + 1;
  36. $link_color_name = substr( $link_color, $index_to_splice );
  37. $link_color = "var(--wp--preset--color--$link_color_name)";
  38. }
  39. $link_color_declaration = esc_html( safecss_filter_attr( "color: $link_color" ) );
  40. $style = "<style>.$class_name a{" . $link_color_declaration . " !important;}</style>\n";
  41. // Like the layout hook this assumes the hook only applies to blocks with a single wrapper.
  42. // Retrieve the opening tag of the first HTML element.
  43. $html_element_matches = array();
  44. preg_match( '/<[^>]+>/', $block_content, $html_element_matches, PREG_OFFSET_CAPTURE );
  45. $first_element = $html_element_matches[0][0];
  46. // If the first HTML element has a class attribute just add the new class
  47. // as we do on layout and duotone.
  48. if ( strpos( $first_element, 'class="' ) !== false ) {
  49. $content = preg_replace(
  50. '/' . preg_quote( 'class="', '/' ) . '/',
  51. 'class="' . $class_name . ' ',
  52. $block_content,
  53. 1
  54. );
  55. } else {
  56. // If the first HTML element has no class attribute we should inject the attribute before the attribute at the end.
  57. $first_element_offset = $html_element_matches[0][1];
  58. $content = substr_replace( $block_content, ' class="' . $class_name . '"', $first_element_offset + strlen( $first_element ) - 1, 0 );
  59. }
  60. return $content . $style;
  61. }
  62. add_filter( 'render_block', 'wp_render_elements_support', 10, 2 );