How To Build WordPress Block Patterns
WordPress is a powerful online publishing tool that allows anyone to easily create and share textual and/or multimedia content. But beyond that, it is also a great professional tool for designers, marketers, and developers regardless of their background and skills.
In short, WordPress can be your most valuable work colleague and help you succeed in a variety of professions.
With that in mind, we have published a series of articles on this blog to help you gain the skills required to be a WordPress developer:
- How to Build Custom Gutenberg Blocks
- How to Create Dynamic Blocks for Gutenberg
- How To Add Meta Boxes and Custom Fields To Posts in Gutenberg
And for those who prefer video content, we also have a free video course: Custom Gutenberg Block Development.
And yes, you can boost your career expectations with Gutenberg development skills, but you don’t necessarily need to be a developer to create advanced layouts on your WordPress website.
WordPress users can take advantage of powerful features that allow them to easily create advanced block layouts with no hassle. In this post we will focus our attention on Block Patterns.
Block Patterns vs. Reusable Blocks vs. Template Parts
Block patterns were first introduced with WordPress 5.5 to allow WordPress users to include complex ready-to-use structures of nested blocks into their content with just a few clicks.
Out of the box, WordPress provides a few built-in block patterns for you to choose from when creating your content. In addition, block themes usually provide more block patterns you can add to your content directly from the block inserter.
For example, the current default theme, Twenty Twenty-Three, provides the following block patterns:
- Call to action
- Default Footer
- Hidden 404
- Hidden Comments
- Hidden No Results Content
- Post Meta
And you are not limited to the patterns provided by WordPress or your theme because the Patterns directory provides tons of ready-to-use block patterns.
But block patterns are not the only feature you can leverage to create block layouts on your WordPress website. The new Gutenberg block editor provides additional tools for you to choose from to create your content layout, including Reusable Blocks and Template Parts. How are these features different from each other? And when prefer one over the others? Let’s dive in.
Block Patterns
Block patterns are predefined groups of blocks that you can add to your content and customize using the same design tools available for the included blocks. Changes made to a block pattern will only affect the specific instance you are editing and won’t be applied to any other instance you may have added to other posts or pages of your website.
You can use block patterns to include prebuilt layouts that you need to customize in place, changing images, text, styles, or adding/removing elements.
Block patterns are reusable, meaning that once you have created your custom block pattern, you can add it anywhere on your website and customize it with just a few clicks using the editor’s built-in controls.
You can browse and insert block patterns from the Patterns tab in the editor’s Block Inserter, or explore the patterns available in the Patterns directory through the pattern explorer that appears when you click on the Explore all patterns button in the Block Inserter.
You’ll find tons of patterns in the Patterns tab of the block inserter, or explore the Block Pattern library directly from the editor’s interface. You can also visit the Block Pattern website, choose a pattern, and click on Copy.
Once you have copied a pattern, paste it into your content and you are done.
Now you can customize the group of blocks included in the pattern without affecting the registered pattern or any additional instance of it on your website.
Reusable Blocks
A Reusable Block is a prebuilt block or group of blocks you can add to any post or page of your website. You can also export reusable blocks to other websites.
Reusable blocks are particularly useful to build elements you may want to include on several pages of your website and/or on different websites. Think of calls to action, promo banners, price tables, and so on.
In the example below, we are creating a reusable block from a Columns block, an Image, a Paragraph, and a Button.
Once you have created a reusable block, you can add it to any page of your website from the Block Inserter.
WordPress considers reusable blocks as wp_block
post type and, as such, stores them in the wp_posts
table.
Once you have created your reusable blocks, you can manage them from the Reusable blocks admin screen. You can access that page in several ways:
- Adding /wp-admin/edit.php?post_type=wp_block to the WordPress URL of your website.
- Clicking on the Manage Reusable blocks button in the Block inserter.
- Clicking on the Manage Reusable blocks button in the Block settings dropdown menu.
Once there, you can
- edit, thrash, or export your block as JSON,
- import reusable blocks from JSON,
- create new reusable blocks.
All changes to a reusable block will be applied to every occurrence of that block on your entire website, regardless of the admin page where the changes are made.
If you use Reusable blocks intensively, don’t miss this great plugin from J. B. Audras.
Template Parts
Before the Gutenberg era, WordPress themes and templates were mainly built in PHP. Solid knowledge of child themes, template hierarchy, and the main front-end development languages were basic requirements to create or customize templates. But things changed with the introduction of block themes.
In block themes and classic themes that have opted into this feature, you can easily create or customize a template or template part with ease in the Site Editor interface. No development skills are required unless, of course, you decide to become a theme developer.
A block template is a list of block items. Examples of block items are the site title, logo, and navigation.
Template parts are specific sections of a page that can be visualized in several locations, such as a header and a footer, and can be displayed on every page of your WordPress website.
You can create and edit template parts through the site editor interface, where you can use all the editing tools available for blocks.
But unlike block patterns and reusable blocks, template parts are intended for areas of the site that do not change frequently.
Differences Between Block Patterns, Reusable Blocks, and Template Parts
To summarise, here are the main differences between the three:
Block Patterns
- Block Patterns are predefined block layouts that you can add to your content and customize using the same tools as the included blocks. Changes made to a block pattern will only affect that single instance of block pattern.
- You can copy and paste block patterns from the Pattern directory.
- You can create new patterns and publish them in the Pattern directory.
Reusable Blocks
- Reusable Blocks are groups of blocks you can use on any post or page of your website. All changes made to a reusable block will be applied to every occurrence of that block on your entire website, regardless of the admin page where the changes are made.
- Reusable blocks are stored in the
wp_posts
table aswp_block
post type. - You can import and export reusable blocks from and to other websites.
Template parts
- Template parts are specific areas of a page that can be displayed in several locations, including Header, Footer, and Sidebar, recurring on several pages of your WordPress website.
- You can create and edit template parts through the site editor interface.
- Template parts are intended for areas of the site that do not change frequently.
How To Create Block Patterns
Along with the block patterns feature, WordPress 5.5 introduced a new API for developers to “create pre-designed blocks of content that can be easily inserted into posts, pages, custom post types, and templates”. The new API provides the register_block_pattern
and register_block_pattern_category
functions to register block patterns and pattern categories.
Starting with WordPress 6.0, you can also register block patterns with a PHP file.
So, at the time of this writing, you have two ways to create a block pattern.
- Using the
register_block_pattern
helper function, - Adding a PHP file to your theme inside a patterns folder.
Creating a Block Pattern With a Plugin
The first method is mainly intended for WordPress developers but is simple enough to be used by non-advanced developers as well.
If you decide to go with the first method, you can create a block pattern using the two new functions register_block_pattern
and register_block_pattern_category
in the PHP file of a plugin or in the functions.php of your theme.
Select or Register a Pattern Category
First, you may want to pick a category for your pattern. With WordPress 6.2, new pattern categories have been added and some existing categories have been modified. At the time of this writing, you can use the following built-in categories:
- Featured (
featured
) - Posts (
posts
) - Text (
text
) - Gallery (
gallery
) - Call to action (
call-to-action
) - Banners (
banner
) - Headers (
header
) - Footers (
footer
) - Team (
team
) - Testimonials (
testimonials
) - Services (
services
) - Portfolio (
portfolio
) - Media (
media
)
If your block pattern does not fall into any of the default categories, you can also register a new category using the register_block_pattern_category
function.
This function accepts two arguments:
$category_name
: Pattern category name including namespace.$category_properties
: An array of category properties.
An example will help you better understand how to register a new pattern category:
if ( function_exists( 'register_block_pattern_category' ) ) {
function my_plugin_register_pattern_category() {
register_block_pattern_category(
'my-pattern-category',
array(
'label' => __( 'My Pattern Category', 'my-plugin-text-domain' ),
'description' => __( 'Simple call to action with a header, an image, a paragraph, and a button.' ),
)
);
}
add_action( 'init', 'my_plugin_register_pattern_category' );
}
Register a Block Pattern
Once the pattern category has been registered, the next step is to register the block pattern itself. You will register the block pattern using the register_block_pattern
helper function as follows:
function my_plugin_register_block_pattern() {
register_block_pattern( 'prefix/pattern-name', $props );
}
add_action( 'init', 'my_plugin_register_block_pattern' );
This function takes two arguments:
$pattern_name
: A machine-readable name in the form ofnamespace/pattern-name
.$pattern_properties
: An array of properties for the pattern.
Here is a list of the currently available pattern properties:
title
(required): A human-readable title for the pattern.content
(required): The HTML markup for the pattern.description
: A text describing the pattern in the inserter. A description is optional but it is recommended as it helps users find the pattern.categories
: An array of one or more registered pattern categories. You have to register a category before you can use it here (see the previous section).keywords
: An array of keywords that help users find the pattern.viewportWidth
: An integer specifying the width of the pattern in the preview.blockTypes
: An optional array of block types that will be used with the pattern.postTypes
: An array of post types that will be allowed to use the pattern.templateTypes
: An array of template types where the pattern makes sense (available since WordPress 6.2).inserter
: A boolean to determine if the pattern should be visible in the block inserter. Set the value tofalse
to hide the pattern. By default, all patterns will appear in the block inserter.
Here is an example of usage of register_block_pattern
:
if ( function_exists( 'register_block_pattern' ) ) {
function my_plugin_register_block_pattern() {
register_block_pattern(
'my-plugin/my-block-pattern',
array(
'title' => _x( 'My awesome pattern', 'Block pattern title', 'my-plugin-text-domain' ),
'categories' => array( 'my-pattern-category' ),
'postTypes' => array( 'post' ),
'content' => '<!-- wp:paragraph --><p>My awesome block pattern</p><!-- /wp:paragraph -->'
)
);
}
add_action( 'init', 'my_plugin_register_block_pattern' );
}
In this code, we used the postTypes
property to make the pattern only available for regular blog posts. You may also set a different value for postTypes
to make it available for different post types. If you have a product
post type and decide to make the pattern only available for that post type, you’ll write:
'postTypes' => array( 'product' ),
Now create a new post (or custom post type), open the block inserter, and click on the Patterns label. You should find a new pattern category (My Pattern Category) with your custom block pattern. Feel free to play around with pattern properties to customize your block patterns.
Now let’s dive a little deeper and try to build a real-world block pattern.
A Real World Example of Block Pattern
Suppose you want to build a block pattern including a heading, an image, a paragraph, and a button.
In the editor, create the layout for your block pattern, then switch to the code editor and copy the markup.
In our example, we have the following code:
<!-- wp:columns -->
<div class="wp-block-columns"><!-- wp:column {"width":"240px"} -->
<div class="wp-block-column" style="flex-basis:240px"><!-- wp:image {"id":25,"sizeSlug":"full","linkDestination":"none","style":{"border":{"radius":{"topLeft":"16px"}}}} -->
<figure class="wp-block-image size-full has-custom-border"><img src="http://wordpress-block-patterns.local/wp-content/uploads/2023/05/placeholder.jpg" alt="" class="wp-image-25" style="border-top-left-radius:16px"/></figure>
<!-- /wp:image --></div>
<!-- /wp:column -->
<!-- wp:column -->
<div class="wp-block-column"><!-- wp:heading {"level":4,"style":{"color":{"text":"#5831f6"}}} -->
<h4 class="wp-block-heading has-text-color" style="color:#5831f6">Your New Home for Modern Web Apps and Sites</h4>
<!-- /wp:heading -->
<!-- wp:paragraph -->
<p>Kinsta is a Cloud Platform designed to help companies and dev teams ship and manage their web projects faster and more efficiently.</p>
<!-- /wp:paragraph --></div>
<!-- /wp:column --></div>
<!-- /wp:columns -->
<!-- wp:buttons {"layout":{"type":"flex"}} -->
<div class="wp-block-buttons"><!-- wp:button {"textAlign":"center","textColor":"base","width":100,"style":{"color":{"background":"#5831f6"},"typography":{"fontSize":"1.36rem"},"border":{"radius":{"topLeft":"0px","topRight":"0px","bottomLeft":"16px","bottomRight":"16px"}}},"fontFamily":"inter"} -->
<div class="wp-block-button has-custom-width wp-block-button__width-100 has-custom-font-size has-inter-font-family" style="font-size:1.36rem"><a class="wp-block-button__link has-base-color has-text-color has-background has-text-align-center wp-element-button" style="border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-left-radius:16px;border-bottom-right-radius:16px;background-color:#5831f6"><strong>View Plans</strong></a></div>
<!-- /wp:button --></div>
<!-- /wp:buttons -->
You can now optimize this code. If you are registering the block pattern with a plugin, you have to change the image URL as follows:
esc_url( plugin_dir_url( __FILE__ ) . 'images/placeholder.jpg' )
This way, WordPress won’t look for the image in the uploads, but in the images folder of your plugin.
You can then use the viewportWidth
property to provide a better preview of the pattern in the block inserter:
'viewportWidth' => 800,
You can also include an array of keywords to help users find your block pattern:
'keywords' => array( 'cta', 'demo', 'kinsta' ),
Another option to help users find the block in searches is adding an array of block types:
'blockTypes' => array( 'core/button' ),
This way, the block pattern will appear in suggestions when a user searches for one of the specified blocks.
The postTypes
property allows you to make the block pattern only available for specific post types. For instance, you could make the pattern only visible for the product
post type:
'postTypes' => array( 'product' ),
Finally, you can add a CSS class to the wrapper of your block pattern.
To do that, you need to create a new Group with the className
attribute:
<!-- wp:group {"className":"my-css-class","layout":{"type":"constrained"}} -->
<div class="wp-block-group my-css-class">
<!-- Your blocks -->
</div>
<!-- /wp:group -->
Note that you need to add the same class name to the following div
element.
For a closer view at block patterns and more examples of code, see also Block patterns in the WordPress.org Theme Handbook.
Creating a Block Pattern With a File
As mentioned above, WordPress 6.0 introduced a new and easier way to add block patterns to your WordPress themes. You can now implicitly register block patterns by declaring them as PHP files under a /patterns folder in your theme’s root.
Say you want to implicitly register the same block pattern built in the previous section in your block theme. In this example, we’ll use the Twenty Twenty-Three theme.
You can set the same parameters as with the previous method but include them in a comment in the file header. In addition, instead of using parameter names in camel case, you will separate the words with a space, and instead of arrays, you’ll use comma-separated list items.
First, deactivate the plugin you used to register the pattern in the previous example. Then create a new my-block-pattern.php file and include the following header:
<?php
/**
* Title: My awesome pattern
* Slug: twentytwentythree/my-block-pattern
* Post Types: post
* Categories: featured, banner
* Viewport Width: 800
* Keywords: Call to action, kinsta
* Block Types: core/buttons
*/
?>
Next, you’ll add the content to your block pattern. You can use the same markup as in our previous example, but first, you’ll need to change it a bit:
<!-- wp:columns -->
<div class="wp-block-columns"><!-- wp:column {"width":"240px"} -->
<div class="wp-block-column" style="flex-basis:240px"><!-- wp:image {"id":25,"sizeSlug":"full","linkDestination":"none","style":{"border":{"radius":{"topLeft":"16px"}}}} -->
<figure class="wp-block-image size-full has-custom-border"><img src="<?php echo esc_url( get_theme_file_uri( 'assets/images/placeholder.jpg' ) ); ?>" alt="" class="wp-image-25" style="border-top-left-radius:16px"/></figure>
<!-- /wp:image --></div>
<!-- /wp:column -->
<!-- wp:column -->
<div class="wp-block-column"><!-- wp:heading {"level":4,"style":{"color":{"text":"#5831f6"}}} -->
<h4 class="wp-block-heading has-text-color" style="color:#5831f6">Your New Home for Modern Web Apps and Sites</h4>
<!-- /wp:heading -->
<!-- wp:paragraph -->
<p>Kinsta is a Cloud Platform designed to help companies and dev teams ship and manage their web projects faster and more efficiently.</p>
<!-- /wp:paragraph --></div>
<!-- /wp:column --></div>
<!-- /wp:columns -->
<!-- wp:buttons {"layout":{"type":"flex"}} -->
<div class="wp-block-buttons"><!-- wp:button {"textAlign":"center","textColor":"base","width":100,"style":{"color":{"background":"#5831f6"},"typography":{"fontSize":"1.36rem"},"border":{"radius":{"topLeft":"0px","topRight":"0px","bottomLeft":"16px","bottomRight":"16px"}}},"fontFamily":"inter"} -->
<div class="wp-block-button has-custom-width wp-block-button__width-100 has-custom-font-size has-inter-font-family" style="font-size:1.36rem"><a class="wp-block-button__link has-base-color has-text-color has-background has-text-align-center wp-element-button" style="border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-left-radius:16px;border-bottom-right-radius:16px;background-color:#5831f6"><strong><?php echo __( 'View plans', 'text-domain' ); ?></strong></a></div>
<!-- /wp:button --></div>
<!-- /wp:buttons -->
The markup is essentially unchanged from the previous example. We have only made two changes.
The placeholder image URL is now generated by the get_theme_file_uri
function:
<?php echo esc_url( get_theme_file_uri( 'assets/images/placeholder.jpg' ) ); ?>
Of course, you should first have placed the placeholder.jpg image in the /assets/images folder of your theme.
The following instruction generates the text you want to translate.
<?php echo __( 'View plans', 'text-domain' ); ?>
Now save your file and create a new post. Your block pattern should appear in the Featured and Banners categories.
Remove Support, Unregister, and Hide Block Patterns
In some scenarios, you may want to perform special actions on block patterns. For example, you may want to replace a core block pattern with a block pattern of your own or unregister a category under certain conditions. Here are the operations you can perform.
1. Remove Support for All Core Block Patterns
First, theme developers can remove support for core block patterns and provide their own set of patterns. To remove core pattern support, you can use the remove_theme_support
function this way:
remove_theme_support( 'core-block-patterns' );
It is recommended to attach the remove_theme_support
function to the after_setup_theme
hook.
2. Unregister a Single Block Pattern
You can also unregister a specific block pattern in case you want to provide a custom alternative or you don’t want it to be used with your theme.
The Patterns API provides the unregister_block_pattern
function for that:
function my_theme_unregister_block_pattern() {
unregister_block_pattern( 'namespace/block-pattern-name' );
}
add_action( 'init', 'my_theme_unregister_block_pattern' );
In case you can also unregister a core block pattern, you will use the following:
function my_theme_unregister_block_pattern() {
unregister_block_pattern( 'core/query-offset-posts' );
}
add_action( 'init', 'my_theme_unregister_block_pattern' );
You will use unregister_block_pattern
with the init
hook.
3. Unregister a Block Pattern Category
You can also unregister a pattern category, hooking the unregister_block_pattern_category
function into the init
hook:
function my_theme_unregister_block_pattern_categories() {
unregister_block_pattern_category( 'pattern-category-name' );
}
add_action( 'init', 'my_theme_unregister_block_pattern_categories' );
Build and Share Block Patterns With the Pattern Creator
You can also create your patterns and share them with the community with a free online tool: The Pattern Creator.
If you have a WordPress.org account, you can access the Pattern Creator from the Pattern directory.
Once there, click on Create new pattern. This will launch a pattern-specific version of the block editor you can use to create your block patterns.
You can also use free images hosted by the Openverse library.
Once you are happy with your changes, you can save the draft or submit the pattern for revision.
You can then go back to the Patterns directory and select My patterns. There you will find all your patterns in three tabs: All, Drafts, and Pending Review.
When you’re finished with your edits, you can share your pattern with the community. Just click on the Submit button in the upper right corner of the editor to submit the pattern for revision (be sure to follow the pattern guidelines before you submit your pattern).
Summary
WordPress turned 20 and the stats tell us that it is still the most widely used CMS in the world, with 63.3% market share as of May 2023.
These numbers prove that WordPress is an excellent publishing tool used by thousands of professionals, developers, and simple bloggers around the world.
Dedicating time and resources to acquiring new skills in WordPress development and learning about advanced features such as custom blocks, reusable blocks, and block patterns could be an excellent investment for your career as a marketer, web designer, or publisher.
And now up to you. Have you already created block patterns? Have you shared any with the community? We would love to see your creations. Leave a comment with a link or your thoughts about block patterns.
The post How To Build WordPress Block Patterns appeared first on Kinsta®.
共有 0 条评论