forked from WordPress/create-block-theme
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme-patterns.php
More file actions
71 lines (65 loc) · 2.04 KB
/
theme-patterns.php
File metadata and controls
71 lines (65 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
class Theme_Patterns {
public static function pattern_from_template( $template, $new_slug = null ) {
$theme_slug = $new_slug ? $new_slug : wp_get_theme()->get( 'TextDomain' );
$pattern_slug = $theme_slug . '/' . $template->slug;
$pattern_content = (
'<?php
/**
* Title: ' . $template->slug . '
* Slug: ' . $pattern_slug . '
* Categories: hidden
* Inserter: no
*/
?>
' . $template->content
);
return array(
'slug' => $pattern_slug,
'content' => $pattern_content,
);
}
public static function escape_alt_for_pattern( $html ) {
if ( empty( $html ) ) {
return $html;
}
// Use WP_HTML_Tag_Processor if available
// see: https://github.com/WordPress/gutenberg/pull/42485
if ( class_exists( 'WP_HTML_Tag_Processor' ) ) {
$html = new WP_HTML_Tag_Processor( $html );
while ( $html->next_tag( 'img' ) ) {
$alt_attribute = $html->get_attribute( 'alt' );
if ( ! empty( $alt_attribute ) ) {
$html->set_attribute( 'alt', self::escape_text_for_pattern( $alt_attribute ) );
}
}
return $html->__toString();
}
// Fallback to regex
// TODO: When WP_HTML_Tag_Processor is availabe in core (6.2) we can remove this implementation entirely.
if ( ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
preg_match( '@alt="([^"]+)"@', $html, $match );
if ( isset( $match[0] ) ) {
$alt_attribute = $match[0];
$alt_value = $match[1];
$html = str_replace(
$alt_attribute,
'alt="' . self::escape_text_for_pattern( $alt_value ) . '"',
$html
);
}
return $html;
}
}
static function escape_text_for_pattern( $text ) {
if ( $text && trim( $text ) !== '' ) {
$escaped_text = addslashes( $text );
return "<?php echo esc_attr_e( '" . $escaped_text . "', '" . wp_get_theme()->get( 'Name' ) . "' ); ?>";
}
}
public static function create_pattern_link( $attributes ) {
$block_attributes = array_filter( $attributes );
$attributes_json = json_encode( $block_attributes, JSON_UNESCAPED_SLASHES );
return '<!-- wp:pattern ' . $attributes_json . ' /-->';
}
}