Categories
Beginners Tutorials

What is a custom block pattern?

A block pattern is a group of blocks, or a block with a predefined content and style.

The purpose of a block pattern is to make it easier and faster to add common design elements and sections to a page or post.

At the time of writing, the block pattern selection is available only when the Gutenberg Plugin is installed and activated.

In the editor toolbar, you will find a new icon which opens a sidebar panel with patterns:

The Block Pattern selection tool is a sidebar in the document settings.

There are four example patterns available by default:

  • Two Columns of Text
  • Two Buttons
  • Cover
  • Two images side by side

How to add a block pattern

To add a new block pattern, themes and plugins can use the new PHP function called register_pattern.

You can read the official documentation for the function here:

register_pattern accepts a name (prefix), a label, and an array with two parameters: Title and content.

  • Title is the name of the pattern that will be visible in the pattern selection panel.
  • Content is the HTML source code of your block pattern.

Example:

register_pattern(
    'theme-prefix/block-pattern-label',
    array(
        'title'   => __( 'Hello Quote' ),
        'content' => '<!-- wp:quote {"className":"hello-block"} --><blockquote class="wp-block-quote hello-block"><p>Hello World of Blocks</p><cite>Carolina</cite></blockquote><!-- /wp:quote -->',
    )
);

To get the correct HTML code to use for your pattern, you can do the following:

  • First, create your block pattern in the editor.
  • Then open the editor toolbar, and select Code editor.

Locate your blocks, copy the code, and add it the content parameter.

<!-- wp:quote {"className":"hello-block"} --><blockquote class="wp-block-quote hello-block"><p>Hello World of Blocks</p><cite>Carolina</cite></blockquote><!-- /wp:quote -->

Since your HTML contains double quotes, “, make sure that the content is wrapped in single quotes, or that you replace the double quotes with \”. Otherwise your code will break.

The preview of the block is created for you automatically.

Custom CSS and identifiers for block patterns

It is worth noting that block patterns have no identifier once they are added to your content.

Even though the patterns have a name and a label, these are not applied to the code.

If you wish to add specific styles, or if you want to be able to identify your block patterns on the front, make sure that you add a custom CSS class while creating the pattern.

Naming block patterns

The name and label of the block pattern must be unique, because otherwise you will overwrite other block patterns.

The title; the visible name of the block pattern, is not unique. So to help identify your patterns, I recommend that you include your brand name, plugin- or theme in the title.

Categories
Tutorials

Adding fonts to the block editor

As we use more and more blocks on our WordPress websites, it is important that the editor match what we see on the front. In this tutorial, we will be adding fonts to the block editor.

A screenshot of the block editor with custom fonts applied for headings and body text.
Custom fonts have been added for headings and body text (paragraphs).

Heads up, this post is a little bit technical if you are a beginner.

I will include an example of how we can use a customizer font option and use that font in the block editor. You can then expand on this basic idea to make it work with your theme or plugin.

This assumes that:

  • Your theme or plugin has a font option using theme mods.
  • You are already using this font on the front of the website (This guide will not cover how to do both).

How to add custom fonts with inline styles

We will be using:

First, we need to check if our theme or plugin is already using the enqueue_block_editor_assets action.

If not, we need to create a new blank .CSS file that we will enqueue. In the example I have named my .CSS file editor-style.css:

function prefix_block_styles() {
wp_enqueue_style( 'prefix-editor-styles', get_theme_file_uri( 'css/editor-style.css' ) );
}
add_action( 'enqueue_block_editor_assets', 'prefix_block_styles' );

Now, if we only had one font to add, and not a customizer option where the user selects fonts, we could enqueue the font like this:

function prefix_block_styles() {
wp_enqueue_style( 'prefix-editor-font', '//fonts.googleapis.com/css?family=Poppins:400,700&display=swap');
}
add_action( 'enqueue_block_editor_assets', 'prefix_block_styles' );

But we want our users to be able to select from several different font combinations. That means that we also need to add our custom font names to the CSS.

The two problems we need to solve are:

  • Applying our dynamic theme mods to the editor style sheet.
  • Overriding the default font that is used in the editor.

The specificity of the Gutenberg style sheet has improved a lot since the early releases. If you are curious about this process and the discussions around CSS specificity, see https://github.com/WordPress/gutenberg/pull/14407

But we still need to override the following:

.edit-post-visual-editor.editor-styles-wrapper,
.editor-post-title__block .editor-post-title__input

And if we have different font options for body text and headings, we also want to override the headings:

.editor-styles-wrapper h1,
.editor-styles-wrapper h2,
.editor-styles-wrapper h3,
.editor-styles-wrapper h4,
.editor-styles-wrapper h5,
.editor-styles-wrapper h6,

Our example code will look like this:

function prefix_block_styles() {
wp_enqueue_style( 'prefix-editor-styles', get_theme_file_uri( 'css/editor-style.css' ) );

$prefix_heading_font = get_theme_mod( 'heading_font', 'Lora' );

$prefix_body_font = get_theme_mod( 'body_font', 
'Roboto' );

wp_enqueue_style( 'prefix-editor-font', '//fonts.googleapis.com/css?family=' . $prefix_heading_font . ':400,700|' . $prefix_body_font . ':400,700&display=swap');

$prefix_custom_css = '
.edit-post-visual-editor.editor-styles-wrapper { font-family:' . 
esc_html( $prefix_body_font ) . ' } 

.editor-post-title__block .editor-post-title__input,
.editor-styles-wrapper h1,
.editor-styles-wrapper h2,
.editor-styles-wrapper h3,
.editor-styles-wrapper h4,
.editor-styles-wrapper h5,
.editor-styles-wrapper h6 { font-family:' .
esc_html( $prefix_heading_font ) . ' } 
';

wp_add_inline_style( 'prefix-editor-styles', $prefix_custom_css );
}
add_action( 'enqueue_block_editor_assets', 'prefix_block_styles' );

First we are adding our empty stylesheet. This is only used so that we can apply our custom css inline later.

Then we are assigning our two theme mods (body and title font family) to variables. This is only for ease of use and to make it easier to read the code.

We use the variables to fetch the correct fonts from Google fonts. I also included two font weights, 400 and 700.

Then we add a third variable, $prefix_custom_css, that holds our custom inline CSS.

Finally we attach the CSS to our style sheet using wp_add_inline_style together with the handle for the style sheet.

Remember to update your prefix :).


Final words

You will probably use a more advanced way of fetching the selected fonts. But for the purpose of this tutorial, I have used wp_enqueue_style directly.

It is recommended to also include some system fonts in the CSS as a fallback.

This method for adding fonts to the block editor is fiddly and not super clean. But it works until the global styles are available in WordPress core.

Categories
Beginners Tutorials

Combining more than one block style

In this guide I have written about how to add block styles using client side rendering. You may be interested in the new quick guide for server side rendering, which is available in WordPress version 5.3 and newer, and contains a lot less code and fewer steps.

In the first example, we only included one custom block style. Adding more styles is straightforward, so lets look at some examples and minor optimization tips.

Adding more than one style to the JavaScript file

We can combine several style options into one JavaScript file as illustrated in the example below:

wp.blocks.registerBlockStyle('core/image', { 
   name: 'slug-filter-grayscale', label: wp.i18n.__('Filter: Grayscale', 'text-domain')
});

wp.blocks.registerBlockStyle('core/image', { 
   name: 'slug-filter-sepia', label: wp.i18n.__('Filter: Sepia', 'text-domain') 
});

We are using wp.blocks.registerBlockStyle separately for each option.
Then we are telling the script which block we want to use: ‘core/image’. Finally we are giving the option a name and a translatable label.

Adding more than one style to the CSS file

Adding additional CSS is even simpler:

.is-style-slug-filter-sepia img {
	filter: sepia(100%);
}

.is-style-slug-filter-grayscale img {
	filter: grayscale(100%);
}

Remember to use the correct selector. In this example we have the is-style-, then the name of the option and img, since we are adding a filter to the image block.

Optimizing the PHP functions

First, we want to check if the theme already uses the hooks ‘enqueue_block_editor_assets’ and / or ‘enqueue_block_assets’. If they are already used, we want to extend the functions and add our code to them, instead of using the hooks twice.

To illustrate this with an example, the theme Twenty Nineteen uses the following code to add extra styles:

/**
 * Enqueue supplemental block editor styles.
 */
function twentynineteen_editor_customizer_styles() {

	wp_enqueue_style( 'twentynineteen-editor-customizer-styles', get_theme_file_uri( '/style-editor-customizer.css' ), false, '1.1', 'all' );

	if ( 'custom' === get_theme_mod( 'primary_color' ) ) {
		// Include color patterns.
		require_once get_parent_theme_file_path( '/inc/color-patterns.php' );
		wp_add_inline_style( 'twentynineteen-editor-customizer-styles', twentynineteen_custom_colors_css() );
	}
}
add_action( 'enqueue_block_editor_assets', 'twentynineteen_editor_customizer_styles' );

What we want to do is enqueue our JavaScript file (block-style.js) inside the function twentynineteen_editor_customizer_styles(). This will save us the effort of creating our own function. 🙂

/**
 * Enqueue supplemental block editor styles.
 */
function twentynineteen_editor_customizer_styles() {

	wp_enqueue_style( 'twentynineteen-editor-customizer-styles', get_theme_file_uri( '/style-editor-customizer.css' ), false, '1.1', 'all' );

	if ( 'custom' === get_theme_mod( 'primary_color' ) ) {
		// Include color patterns.
		require_once get_parent_theme_file_path( '/inc/color-patterns.php' );
		wp_add_inline_style( 'twentynineteen-editor-customizer-styles', twentynineteen_custom_colors_css() );
	}

	wp_enqueue_script( 'slug-block-styles-script', get_theme_file_uri( '/js/block-styles.js' ), array( 'wp-blocks', 'wp-i18n' ) );
	wp_set_script_translations( 'slug-block-styles-script', 'text-domain' );
}
add_action( 'enqueue_block_editor_assets', 'twentynineteen_editor_customizer_styles' );

To recap, we are:

  • Adding the block-styles.js which adds the style options to the WordPress editor.
  • Adding an array of existing block editor scripts that we need to include for our code to work:
    wp-blocks, for the block itself, and wp-il8n, for the translation function.
  • Enabling the translations with wp_set_script_translations, the script name, and the text domain.

There is more than one way to add the styles

We still need to add our custom CSS, and there is more than one way to do this.

  • You can enqueue your CSS file (which only contains the custom block styles) with the ‘enqueue_block_assets’ hook, as we did in the previous example.
  • If your theme is already using ‘enqueue_block_editor_assets’ to include styles for the editor, you have the option to add your CSS to your themes existing .css files. This means that you have to add the styles twice: Once in the file that is used for the editor, and once for the front end.

Which option to choose depends on the size of the CSS. In this example we are only adding two styles, so the second option might be better since we are avoiding the additional http request. But if the file is larger, -or if you really don’t want to have to repeat yourself, the first option might be better.