Skip to content

Commit

Permalink
Block Patterns: Also load patterns from bare HTML files
Browse files Browse the repository at this point in the history
Alternative take based on #36751 (comment)
  • Loading branch information
mcsf committed Nov 23, 2021
1 parent 23e44ef commit d592853
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions lib/block-patterns.php
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,61 @@ function _register_theme_block_patterns() {
// if applicable.
foreach ( wp_get_active_and_valid_themes() as $theme ) {
$dirpath = $theme . '/patterns/';
if ( file_exists( $dirpath ) ) {
$files = glob( $dirpath . '*.html' );
if ( $files ) {
foreach ( $files as $file ) {
// Parse pattern slug from file name.
if ( ! preg_match( '#/(?P<slug>[A-z0-9_-]+)\.html$#', $file, $matches ) ) {
continue; // FIXME: Consider logging notice.
}
// Example name: twentytwentytwo/query-grid-posts.
$pattern_name = get_stylesheet() . '/' . $matches['slug'];

$pattern_data = get_file_data( $file, $default_headers );

// Title is a required property.
if ( ! $pattern_data['title'] ) {
continue;
}

// For properties of type array, parse data as comma-separated.
foreach ( array( 'categories', 'keywords', 'blockTypes' ) as $property ) {
$pattern_data[ $property ] = array_filter(
preg_split(
'/[\s,]+/',
(string) $pattern_data[ $property ]
)
);
}

// Parse properties of type int.
foreach ( array( 'viewportWidth' ) as $property ) {
$pattern_data[ $property ] = (int) $pattern_data[ $property ];
}

// Remove up empty values, so as not to override defaults.
foreach ( array_keys( $default_headers ) as $property ) {
if ( empty( $pattern_data[ $property ] ) ) {
unset( $pattern_data[ $property ] );
}
}

// The actual pattern is everything following the leading comment.
$raw_content = file_get_contents( $file );
$token = '-->';
$pattern_data['content'] = substr(
$raw_content,
strpos( $raw_content, $token ) + strlen( $token )
);
if ( ! $pattern_data['content'] ) {
continue;
}

register_block_pattern( $pattern_name, $pattern_data );
}
}
}
if ( file_exists( $dirpath ) ) {
$files = glob( $dirpath . '*.php' );
if ( $files ) {
Expand Down

0 comments on commit d592853

Please sign in to comment.