Skip to content

#[AsBlockPattern]

Register a class as a WordPress block pattern.

Signature

php
#[Attribute(Attribute::TARGET_CLASS)]
final readonly class AsBlockPattern
{
    public function __construct(
        public string $name,
        public string $title,
        public array $categories = [],
        public array $keywords = [],
        public array $blockTypes = [],
        public ?string $description = null,
        public ?string $template = null,
        public int $viewportWidth = 1200,
        public bool $inserter = true,
    ) {}

    public function getTemplatePath(): string {}
}

Parameters

ParameterTypeDefaultDescription
namestringPattern name with namespace
titlestringDisplay title (required)
categoriesstring[][]Pattern categories
keywordsstring[][]Search keywords
blockTypesstring[][]Associated block types
description?stringnullPattern description
template?stringAuto-resolvedTemplate path
viewportWidthint1200Preview viewport width
inserterbooltrueShow in block inserter

Usage

Basic Pattern

php
<?php

namespace App\Patterns;

use Studiometa\Foehn\Attributes\AsBlockPattern;

#[AsBlockPattern(
    name: 'theme/hero-with-cta',
    title: 'Hero with CTA',
    categories: ['featured'],
)]
final class HeroWithCta {}

Template at patterns/hero-with-cta.twig:

twig
<!-- wp:cover {"dimRatio":50} -->
<div class="wp-block-cover">
    <div class="wp-block-cover__inner-container">
        <!-- wp:heading {"level":1} -->
        <h1>Welcome</h1>
        <!-- /wp:heading -->
    </div>
</div>
<!-- /wp:cover -->

With Dynamic Content

Implement BlockPatternInterface:

php
<?php

namespace App\Patterns;

use Studiometa\Foehn\Attributes\AsBlockPattern;
use Studiometa\Foehn\Contracts\BlockPatternInterface;

#[AsBlockPattern(
    name: 'theme/latest-posts',
    title: 'Latest Posts',
    categories: ['posts'],
)]
final class LatestPosts implements BlockPatternInterface
{
    public function context(): array
    {
        return [
            'posts' => \Timber\Timber::get_posts([
                'posts_per_page' => 3,
            ]),
        ];
    }
}

Full Configuration

php
#[AsBlockPattern(
    name: 'theme/pricing-table',
    title: 'Pricing Table',
    categories: ['featured', 'pricing'],
    keywords: ['price', 'plans'],
    blockTypes: ['core/group'],
    description: 'A pricing comparison table',
    template: 'patterns/pricing',
    viewportWidth: 1400,
    inserter: true,
)]

Template Resolution

Default: theme/hero-sectionpatterns/hero-section.twig

Custom with template parameter.

Released under the MIT License.