create-block-theme/admin/create-theme/theme-patterns.php

71 lines
2 KiB
PHP
Raw Normal View History

<?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' );
2023-03-01 13:24:47 +05:30
$pattern_slug = $theme_slug . '/' . $template->slug;
2023-02-22 16:46:42 +05:30
$pattern_content = (
2023-03-01 13:24:47 +05:30
'<?php
2023-02-22 16:46:42 +05:30
/**
2023-03-01 13:24:47 +05:30
* Title: ' . $template->slug . '
* Slug: ' . $pattern_slug . '
2023-02-22 16:46:42 +05:30
* Categories: hidden
* Inserter: no
*/
?>
2023-03-01 13:24:47 +05:30
' . $template->content
2023-02-22 16:46:42 +05:30
);
2023-03-01 13:24:47 +05:30
return array(
'slug' => $pattern_slug,
'content' => $pattern_content,
2023-02-22 16:46:42 +05:30
);
}
2023-03-01 13:24:47 +05:30
public static function escape_alt_for_pattern( $html ) {
if ( empty( $html ) ) {
2023-02-22 16:46:42 +05:30
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' );
2023-03-01 13:24:47 +05:30
if ( ! empty( $alt_attribute ) ) {
2023-02-22 16:46:42 +05:30
$html->set_attribute( 'alt', self::escape_text_for_pattern( $alt_attribute ) );
}
}
return $html->__toString();
}
2023-03-01 13:24:47 +05:30
2023-02-22 16:46:42 +05:30
// 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' ) ) {
2023-03-01 13:24:47 +05:30
preg_match( '@alt="([^"]+)"@', $html, $match );
2023-02-22 16:46:42 +05:30
if ( isset( $match[0] ) ) {
$alt_attribute = $match[0];
2023-03-01 13:24:47 +05:30
$alt_value = $match[1];
$html = str_replace(
2023-02-22 16:46:42 +05:30
$alt_attribute,
'alt="' . self::escape_text_for_pattern( $alt_value ) . '"',
$html
);
}
return $html;
}
}
2023-03-01 13:24:47 +05:30
static function escape_text_for_pattern( $text ) {
if ( $text && trim( $text ) !== '' ) {
return "<?php echo esc_attr_e( '" . $text . "', '" . wp_get_theme()->get( 'Name' ) . "' ); ?>";
2023-02-22 16:46:42 +05:30
}
}
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 . ' /-->';
}
}