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