Creating a simple block pattern plugin for the Gutenberg editor

Gutenberg has the potential to be an extremely powerful site building tool. Each release brings it closer and closer to full site editing. Imagine being able to rearrange your header, add a sidebar, or combine different layouts inside your footer without needing to rely on your theme to provide multiple options.

Part of this new vision for WordPress includes block patterns, which are combinations of blocks you can create and share to help people make rich, unique site layouts. The possibilities are exciting. Many third-party plugins already provide these feature, so I’m stoked to see them being included in the core editing experience.

Gutenberg 7.8 introduced a new (WIP, subject to change) API to register custom block patterns:

register_pattern(
    'my-plugin/my-awesome-pattern',
    array(
        'title'   => __( 'Two buttons', 'my-plugin' ),
        'content' => "<!-- wp:buttons {\"align\":\"center\"} -->\n<div class=\"wp-block-buttons aligncenter\"><!-- wp:button {\"backgroundColor\":\"very-dark-gray\",\"borderRadius\":0} -->\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link has-background has-very-dark-gray-background-color no-border-radius\">" . esc_html__( 'Button One', 'my-plugin' ) . "</a></div>\n<!-- /wp:button -->\n\n<!-- wp:button {\"textColor\":\"very-dark-gray\",\"borderRadius\":0,\"className\":\"is-style-outline\"} -->\n<div class=\"wp-block-button is-style-outline\"><a class=\"wp-block-button__link has-text-color has-very-dark-gray-color no-border-radius\">" . esc_html__( 'Button Two', 'my-plugin' ) . "</a></div>\n<!-- /wp:button --></div>\n<!-- /wp:buttons -->",
    )
);

It really only contains two things: a name for your pattern, and the raw HTML output that you can copy and paste from the Code editor view. This means you can design your patterns straight in the editor, no coding knowledge required.

When you add a new pattern to your site, they show up in a new sidebar in your editor:

The new (temporary) patterns sidebar. See more designs on GitHub.

Let’s look at making a new pattern.

I want to create a simple text pattern that contains a larger introductory paragraph, and two columns of paragraphs below.

The first thing I do is add a new column block to the editor:

I want the intro paragraph to be a little wider than the two paragraphs I’m going to put below it, so I choose the 70/30 option.

I enter my first paragraph, and increase the font size to 28px. I leave the second column blank.

Now, I add another column block, this time choosing the 50/50 option, and add my two paragraphs.

That looks good. Let’s go over to the Code view and grab that raw HTML:

Escape it, and then plop it inside register_pattern:

register_pattern(
    'mels-gutenberg-block-patterns/intro-two-columns',
    array(
        'title'   => __( 'Intro paragraph with two columns', 'mels-gutenberg-block-patterns' ),
        'content' => "<!-- wp:columns -->\n<div class=\"wp-block-columns\"><!-- wp:column {\"width\":70} -->\n<div class=\"wp-block-column\" style=\"flex-basis:80%\"><!-- wp:paragraph {\"customFontSize\":28} -->\n<p style=\"font-size:28px\">Driving empathy maps and possibly surprise and delight. Target mobile-first design with the aim to build ROI.</p>\n<!-- /wp:paragraph --></div>\n<!-- /wp:column -->\n\n<!-- wp:column {\"width\":33.33} -->\n<div class=\"wp-block-column\" style=\"flex-basis:33.33%\"></div>\n<!-- /wp:column --></div>\n<!-- /wp:columns -->\n\n<!-- wp:columns -->\n<div class=\"wp-block-columns\"><!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:paragraph -->\n<p>Informing innovation and then surprise and delight. Driving custom solutions and possibly think outside the box. Create awareness with a goal to funnel users. Lead relevant and engaging content with the possibility to infiltrate new markets.</p>\n<!-- /wp:paragraph --></div>\n<!-- /wp:column -->\n\n<!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:paragraph -->\n<p>Amplifying innovation with the possibility to target the low hanging fruit. Consider dark social but innovate. Creating a holistic approach in order to be on brand. Leading empathy maps but be CMSable. Repurposing branding.</p>\n<!-- /wp:paragraph --></div>\n<!-- /wp:column --></div>\n<!-- /wp:columns -->",
    )
);

(I’ve used onlinestringtools.com to escape the raw html output, but there are also code editor tools that can do this.)

Then, we can wrap our registered pattern in a plugin:

<?php
/**
 * Plugin Name: Mel's Super Rad Patterns
 * Description: A simple plugin to demonstrate how to add Block Patterns to Gutenberg.
 * Version: 1.0
 * Author: Mel Choyce
 */

/**
 * Register Custom Block Styles
 */
function mels_patterns_register_block_patterns() {
    if ( function_exists( 'register_pattern' ) ) {
    /**
    * Register block patterns
    */
        register_pattern(
            'mels-gutenberg-block-patterns/intro-two-columns',
            array(
                'title'   => __( 'Intro paragraph with two columns', 'mels-gutenberg-block-patterns' ),
                'content' => "<!-- wp:columns -->\n<div class=\"wp-block-columns\"><!-- wp:column {\"width\":70} -->\n<div class=\"wp-block-column\" style=\"flex-basis:80%\"><!-- wp:paragraph {\"customFontSize\":28} -->\n<p style=\"font-size:28px\">Driving empathy maps and possibly surprise and delight. Target mobile-first design with the aim to build ROI.</p>\n<!-- /wp:paragraph --></div>\n<!-- /wp:column -->\n\n<!-- wp:column {\"width\":33.33} -->\n<div class=\"wp-block-column\" style=\"flex-basis:33.33%\"></div>\n<!-- /wp:column --></div>\n<!-- /wp:columns -->\n\n<!-- wp:columns -->\n<div class=\"wp-block-columns\"><!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:paragraph -->\n<p>Informing innovation and then surprise and delight. Driving custom solutions and possibly think outside the box. Create awareness with a goal to funnel users. Lead relevant and engaging content with the possibility to infiltrate new markets.</p>\n<!-- /wp:paragraph --></div>\n<!-- /wp:column -->\n\n<!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:paragraph -->\n<p>Amplifying innovation with the possibility to target the low hanging fruit. Consider dark social but innovate. Creating a holistic approach in order to be on brand. Leading empathy maps but be CMSable. Repurposing branding.</p>\n<!-- /wp:paragraph --></div>\n<!-- /wp:column --></div>\n<!-- /wp:columns -->",
            )
        );
    }
}
add_action( 'init', 'mels_patterns_register_block_patterns' );

…And now our new pattern shows up in the sidebar inside Gutenberg:

Whoo! 🎉 Party time 🕺


The possibilities are pretty endless. You can stick with simpler patterns, or combine even more blocks and patterns to create rich, complex layouts:

Want to learn more about combining blocks to make unique designs in WordPress? Attend WPBlockTalk, this upcoming Thursday. It’s free and online, so you can watch from anywhere!

3 responses to “Creating a simple block pattern plugin for the Gutenberg editor”

  1. גוטנברג בגירסה 7.7 הציג אפשרות חדשה ליצירת “מערך בלוקים” כלומר איחוד בלוקים יחד לשימוש חוזר. בפוסט הזה אבדוק איך עושים זאת.

    הפוסט המקורי נמצא בבלוב של Mel Choyce – כאן

    ג’סטין טאדלטק כתב על כך גם כאן

    לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית גולר מונפרר סוברט לורם שבצק יהול, לכנוץ בעריר גק ליץ, לפרומי בלוף קינץ תתיח לרעח. לת צשחמי צש בליא, מנסוטו צמלח לביקו ננבי,

    קולהע צופעט למרקוח איבן איף, ברומץ כלרשט מיחוצים. קלאצי לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי.

    לורם איפסום דולור סיט אמט, קולהע צופעט למרקוח איבן איף, ברומץ כלרשט מיחוצים. קלאצי קולורס מונפרד אדנדום סילקוף, מרגשי ומרגשח. עמחליף להאמית קרהשק סכעיט דז מא, מנכם למטכין נשואי מנורך. קולהע צופעט למרקוח איבן איף, ברומץ כלרשט מיחוצים. קלאצי סחטיר בלובק. תצטנפל בלינדו למרקל אס לכימפו, דול.

    לאחר יצירת התוסף, הכנסתו לקובץ זיפ והתקנותו באתר, אפשר לראות את הפריסה החדשה בספרייה מצד שמאל. מצורף צילום מסך:

  2. Es ist leider schon eine Weile her, dass ich die Muße gefunden habe, mich einem neuen Blogbeitrag zu widmen. 2020 hat sich turbulenter entwickelt, als wir es uns alle noch vor ein paar Wochen hätten vorstellen können. Auch unsere Pläne haben sich kurzerhand geändert und wir müssen nur ein paar Tage vor dem Lockdown hier in Neuseeland eine neue Wohnung finden. Das hat zum Glück auch sehr unkompliziert geklappt und inzwischen haben wir wieder in einem einigermaßen „normalen“ Alltag zurückgefunden.
    Jetzt aber genug Vorwort, denn auch in der WordPress- und Gutenberg-Entwicklung hat sich einiges getan. Zum Beispiel können Theme- und Plugin-Autoren seit der Gutenberg-Plugin Version 7.8 Block Patterns erstellen.
    Block Patterns – Ein erster Überblick
    Bisher konnte man im Gutenberg-Editor nur einzelne Blöcke einfügen. Für Blogbeiträge oder einfach aufgebaute Seiten funktioniert das auch prima. Wenn man aber etwas komplexere Layouts verwenden möchte, z.B. mit ineinander verschachtelten Blöcken, wird das ganze schon schwieriger.
    Es kann sehr viel Zeit kosten ein mehrspaltiges Layout mit Inhalten aufzubauen und alle Blöcke einzeln auszuwählen und auf der Seite einzubinden.
    Die Lösung für dieses Problem sind die neuen Block Patterns. Block Patterns sind vorbereitete Block-Kombination mit Beispielinhalten.

    Beispiel Block Patterns vom Block Patterns Feature auf Github
    Sie können im Editor als in einer Vorschauansicht angeschaut und ausgewählt werden.
    Block Patterns können im Editor ausgewählt werden.
    So kann man mit einem Klick auch aufwendigere Layouts auf einer Seite platzieren. Jetzt muss man nur noch die Beispielinhalte mit den eigenen Inhalten austauschen.
    Was sind die Vorteile von Block Patterns?
    Der große Vorteil der Block Patterns ist, dass sie sehr unkompliziert erstellt werden können. Plugin- oder Themeautoren müssen die Layouts nur selbst im Editor erstellen, den HTML-Code der erstellten Blöcke kopieren und in ein Code-Snippet im Plugin oder Theme einbinden. Mel Choyce erklärt diesen technischen Teil sehr schön auf ihrem Blog.
    WordPress-Nutzern wird mit den vorbereiteten Layoutelementen leichter gemacht, auch komplexere Layouts relativ schnell aufzubauen. Die Arbeit im Gutenberg-Editor wird durch das neue Block Patterns Feature sehr viel benutzerfreundlicher.
    Wie wird die Entwicklung der Block Patterns weitergehen?
    Das Konzept der Block Patterns ist momentan noch ganz neu und steckt noch in der Entwicklung. Derzeit kannst du Patterns nur nutzen, wenn du das Gutenberg-Plugin aktiviert hast. Soweit ich informiert bin, sollen Block Patterns neben anderen neuen Features aber schon in die kommende WordPress-Version 5.5 (geplant für den 11. August) integriert werden.
    Wir arbeiten gerade auch an unseren erste Block Patterns für Aino.

    Erste Block-Pattern Designs für unser Aino Theme und Blocks-Plugin.
    Sobald unser Aino Block-Plugin auf WordPress.org zur Verfügung steht, werden dort die ersten Block Patterns integriert sein. Wir haben uns dazu entschlossen unsere Block Patterns ins Plugin zu intergieren und nicht ins Theme, da für unsere Patterns die Aino-Blöcke benötigt werden.
    Deine Meinung und Fragen
    Hattest du schon von dem neuen Block Patterns in WordPress gehört? Gefällt dir das Konzept und denkst du, dass es die Arbeit mit WordPress erleichtern wird? Wer wird deiner Ansicht nach am meisten von diesem neuen Editor-Feature profitieren?
    Schreibe mir doch deine Einschätzung zu den neuen Block Patterns und der Entwicklung vom Gutenberg-Editor allgemein in einem Kommentar. Ich würde mich sehr über deine Meinung freuen. Und melde dich auch, wenn du Fragen zum Thema Block Patterns hast.

  3. It’s been a while since I felt calm enough to sit down and write something here on the blog. True writers block I guess. It didn’t feel good to be so quiet here and not share. But I think it’s also important to acknowledge that 2020 has brought a lot more challenges to us than anyone would have ever expected just a few short months ago.
    Everyone’s plans changed. We thought we could be in Europe right now, connecting with friends at WordCamp Europe and spending time with our families. Instead we had to quickly find a new apartment before New Zealand went into a lockdown at the end of March.
    By now we found a new “normal” and concentrating on our work is also a good distraction from all the difficult news surrounding all of us.
    But now enough talking about world events and personal challenges. Over the last months a lot has happened in the WordPress and Gutenberg hemisphere as well.
    One of those exciting new features that arrived in the block editor with the 7.8 Gutenberg plugin update are Block Patterns.
    What are block patterns?
    Until recently the only available option to create layouts in the block editor was to add block by block to your page or post.
    With block patterns plugin and theme authors it can now prepare a collection of (nested) blocks for their users. This way we can provide ready-to-use website snippets like featured header sections, a team section, testimonials or more advanced multicolumn layouts.

    Sample Block Patterns via the Gutenberg development on Github.
    Block Patterns can be selected directly in the editor.
    Users don’t have to build the layouts in the editor themselves, but can instead choose a block pattern from a preview area and with one click have the complete layout available on their page including the block pattern sample content. Users then only need to exchange the sample content with their own content.
    What advantages can block patterns offer?
    Using block patterns will save WordPress users a lot of time creating their website. Block patterns also make it easier for creators to offer more complex block combinations to their audience. It’s a very flexible solution, since certain blocks of a block pattern can be deleted and exchanged with other blocks. It’s also possible insert different block patterns onto a page and then play around with their positioning (this is easiest, if each block pattern is grouped in one main parent block).
    Great about block patterns is also that it’s not too complicated to create them from the technical side. Theme and plugin authors only need to build a layout in the editor and copy the HTML outcome into their theme or plugin code. Mel Choyce wrote a great technical tutorial explaining how to create block patterns.
    Since block patterns make it much easier for users to include more complex layouts on their website, the editor experience becomes a lot more user friendly.
    What can we expect from block patterns going forward?
    At the moment block patterns are still very new and under development. You need the Gutenberg plugin to be able to use them. But with the upcoming WordPress version 5.5 (the release date is planned for August 11th) they will be available to use by default.
    We are working on our first block patterns for our Aino theme and blocks collection.

    First Aino block pattern designs.
    As soon as our free Aino blocks plugin is available on WordPress.org, we will offer first block patterns for the Aino theme and blocks.
    We decided to include our block patterns in the Aino blocks plugin, since users will need the Aino blocks for the patterns to work.
    What do you think?
    Did you already hear about WordPress block patterns and what do you think about this new feature? Are you excited and do you think it’s an important improvement for the editor?
    Which WordPress user group will benefit the most from block patterns in your opinion?
    Let me know your opinion and thoughts about the new features that are getting integrated in the Gutenberg editor. And please also ask any question you might have. I would love to hear from you.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Find out more about Webmentions.)