create-block-theme/includes/create-theme/theme-patterns.php
2025-04-15 08:08:28 -04:00

51 lines
1.4 KiB
PHP

<?php
class CBT_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
<?php
/**
* Title: {$template->slug}
* Slug: {$pattern_slug}
* Inserter: no
*/
?>
{$template->content}
PHP;
return array(
'slug' => $pattern_slug,
'content' => $pattern_content,
);
}
public static function escape_alt_for_pattern( $html ) {
if ( empty( $html ) ) {
return $html;
}
$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();
}
public static function escape_text_for_pattern( $text ) {
if ( $text && trim( $text ) !== '' ) {
$escaped_text = addslashes( $text );
return "<?php 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 . ' /-->';
}
}