Resources for block theme development

With WordPress 5.8 launching on July 20th, it seems like a great time to round up some resources to help theme authors prepare for the future. By now, you’ve probably heard about block themes and the upcoming future of full site editing. Perhaps you have even begun to explore creating a block theme or adapting your current theme to some of the new features, like template editing mode. Whether you’re just starting out or already deep in the block theme world, the following resources should help you be aware of what’s to come and how to get involved in shaping the future. If you’re looking for a quick snapshot, it’s recommended to review the following for 5.8: 

Curate your information

Since block themes are currently evolving along with the features to support them, it’s helpful to start by figuring out what will help you stay up to date with the latest happenings, as that makes sense for you. Here are a few options:

Dive into resources

Outside of knowing the latest, it helps to know what the best practices are to follow. The following should give you great places to start: 

Learn from and with others

Since this is an area that folks across the WordPress community are diving into, there are some fantastic ways to keep in touch with what others are experimenting with, how they are solving problems, how they are getting started, and more. Especially during a time where we can’t meet up and look over someone’s shoulder at a WordCamp, hopefully these resources help bridge that divide even a tiny bit. 


While these are the resources we found most useful, we’d love to hear from you too. What resources have been helpful for you to explore block themes and the various pathways leading up to full site editing? Share in the comments so we can all learn together. 

Universal Themes: Customization

Making Global Styles and the Customizer work together

In the last post we shared the idea of a “universal” theme. This post looks at how we can use classic WordPress tools (in this case the Customizer) to customize a block theme, while saving these changes in Global Styles – making a universal theme!

Global Styles Everywhere

Block themes use a theme.json file to define many aspects of the theme, e.g. color palettes and typography. Gutenberg provides a tool to edit these settings (called Global Styles). When a user changes these values in the Global Styles UI, the changes are not saved back into the theme.json file but instead are saved to a Custom Post Type (CPT) in WordPress. Because this CPT can be modified using WordPress APIs, this gives us the power to make changes to Global Styles without relying on the interface in Gutenberg.

This simple idea is the basis for the color and typography customization options we have added to our universal theme Blockbase. The rest is just implementation details…

Implementation details!

When the Customizer loads, we create two new sections:

  1. Colors
  2. Fonts
$wp_customize->add_section(
	'customize-global-styles-colors',
	array(
		'capability'  => 'edit_theme_options',
		'description' => sprintf( __( 'Color Customization for %1$s', 'blockbase' ), $theme->name ),
		'title'       => __( 'Colors', 'blockbase' ),
	)
);
$wp_customize->add_section(
	'customize-global-styles-fonts',
	array(
		'capability'  => 'edit_theme_options',
		'description' => sprintf( __( 'Font Customization for %1$s', 'blockbase' ), $theme->name ),
		'title'       => __( 'Fonts', 'blockbase' ),
	)
);

In each of these sections we create new settings and controls – each setting and control relates to a color/font option in Global Styles. We read the content of the theme.json file and use this to populate the settings in the Customizer. There is a helpful function in Gutenberg which merges together the theme.json settings with any user settings:

WP_Theme_JSON_Resolver_Gutenberg::get_merged_data()->get_raw_data();

We read in an array of color palettes from the theme.json file and display these inside the “Colors” section:

Previews

One of the powers of Global Styles is that it relies on CSS variables. This makes it very easy for us to update the Customizer preview when the controls are changed. Some simple javascript injects new values for these CSS variables into the page, meaning that the preview updates instantly.

First we bind a listener to the control:

// For each of the palette items add a listener
userColorPalette.forEach( ( paletteItem ) => {
	const settingName = userColorSectionKey + paletteItem.slug;
	wp.customize( settingName, ( value ) => {
		value.bind( ( newValue ) => {
			paletteItem.color = newValue;
			blockBaseUpdateColorsPreview( userColorPalette );
		} );
	} );
} );

This updates the global variable userColorPalette, which we then use to create our CSS variables:

function blockBaseUpdateColorsPreview( palette ) {
	// build the CSS variables to inject
	let innerHTML = ':root,body{';
	palette.forEach( ( paletteItem ) => {
		innerHTML += `--wp--preset--color--${ paletteItem.slug }:${ paletteItem.color };`;
	} );
	innerHTML += ';}';

	// inject them into the body
	const styleElement = document.getElementById(
		'global-styles-colors-customizations-inline-css'
	);
	styleElement.innerHTML = innerHTML;
}

Saving

Customizer settings are usually saved in a site option or a theme mod. Since we are building a universal theme, we need to save these changes into Global Styles so that they are reflected in the Site Editor. The easiest way we found to achieve this was to hook into the customize_save_after action, read the settings from the controls, and then update the Global Styles CPT with the new settings. This code is used to get and read the CPT:

WP_Theme_JSON_Resolver_Gutenberg::get_user_custom_post_type_id();
get_post( $user_custom_post_type_id );
json_decode( $user_theme_json_post->post_content );

Once you have the CPT in JSON form it’s simply a case of adding the new settings to it, and saving them back into the CPT:

$user_theme_json_post_content->settings->color->palette = $this->user_color_palette;

wp_update_post( json_encode( $user_theme_json_post_content ) );

Color Palettes

Color palettes are simply combination of color settings. When a user selects a palette we simply change all of the associated colors at once. This can be done with the Javascript API:

wp.customize.control( userColorSectionKey ).setting.set( color );

How can I use this?

The code above is just pseudo code, to explain the concepts. For a fully working example see Blockbase freely available in our free themes repository. This code has a GPL license and can therefore be copied and distributed freely.

However, if you are interested in building a universal theme I would encourage you to use Blockbase as a parent theme. This will mean you get all future improvements to your theme for free!

Ephitah

The Customizer gets a bad rap, and it’s true that it is clunky when compared to the direct manipulation that is possible with Gutenberg. Nevertheless, building these kinds of tools to update Global Styles without the framework of the Customizer would have been much more involved. There is some satisfaction in being able to take advantage of all the hard work that has gone into the Customizer in its final years!

Theme patterns for the Site Editor

Learn how to use Template Part and Query Loop patterns to provide users with more design options.

We’ve been bundling block patterns with all of our themes for quite a while now, but recent improvements to the Template Part and Query Loop blocks has opened up a whole new world for how patterns can be used.

Both blocks can now display a carousel of block patterns in their setup state, allowing users to choose between a menu of pre-designed versions of these blocks. These patterns can be bundled with your theme, so that users have a wide range of pre-designed header, query, and footer options available to choose from in the Site Editor:

The only difference between these and other patterns you’d build is that they include a special blockTypes property to let Gutenberg know which block to associate them with. Here’s a simplified example:

register_block_pattern(
	'theme/pattern-slug',
	array(
		'title'       => _x( 'Pattern Title' 'theme-slug' ),
		'blockTypes'  => array( 'core/template-part/header' ),
		'content'     => '<!-- Your Pattern Markup -->'
	)
);

The markup above specifies that this pattern should be surfaced for a Header template part block. The value there would core/template-part/footer or core/query if you were designing a pattern for those blocks instead. (This property also powers pattern transforms, but that’s a topic for another time).

Once you register a pattern that way, it will show up in the carousel for the specified block. It’s as simple as that!

There are already a few Query Loop patterns bundled with Core today that use this method, and the header patterns shown in the video above are actually from a Gutenberg PR I’m working on as well. I’ve prepared a quick code example using our in-progress Quadrat theme to show how they could be bundled — we definitely plan on including a handful of these sorts of patterns in our block themes moving forward.

https://github.com/Automattic/themes/pull/4104

When combined together, Header, Query Loop, and Footer patterns allow you to mix-and-match pre-designed sections to create your entire website. I’m truly excited to see not only how themes use this feature, but how the Pattern Directory might provide hundreds more options for these blocks. This feels groundbreaking for WordPress, and I can’t wait to see how it turns out.

Universal themes: Some ideas

With the Full Site Editing project well underway, theme developers need to be thinking about what the future holds for themes. 

Why block themes?

To take advantage of the Site Editor, themes need to be built out of blocks – this is why we need block themes. Block themes are an entirely new way of creating themes. Classic themes bundle all of the code needed to control the presentation and functionality of the site, with the theme itself. This often means that themes contain extra code to add features (e.g. a slideshow) as well CSS to control the layout.

With block themes, much of the theme’s functionality and presentation is provided by Gutenberg. This means that themes have a shared set of features and style rules, which brings several benefits for users:

  1. The user experience for customising themes is more consistent.
  2. When users switch themes, they won’t lose features, as Gutenberg provides the same features to all themes.
  3. Users can mix and match aspects of different themes – e.g. the header of one theme with the footer of another.

There are also some benefits for developers:

  1. Less code is needed to build a highly functioning theme.
  2. Features that are used by many themes are now provided by the community, so that everyone benefits from the work done to maintain and improve them.

Can I use block themes today?

Block themes are the future and they will provide users great tools when Full Site Editing launches. For now, only those who are running the latest Gutenberg plugin and are willing to use experimental features like the Site Editor are able to use block themes.

Although the Site Editor is not yet ready, many aspects Full Site Editing will be available in WordPress 5.8. There is an opportunity to start building some form of block themes before Site Editor is ready.

Two editing modes

Full Site Editing brings a new editing mode for themes. For the sake of this article we’ll call the current editing mode, “classic” (Site Editor disabled) and the Full Site Editing mode, “FSE” mode (Site Editor enabled).

Users with classic themes will (probably) need to switch themes if they want to start using the Full Site Editing features. However if we can build block themes in a way that works in “classic” mode, then users will be able to take advantage of Full Site Editing once the tools are available. We have been calling themes like this “universal” themes.

Universal themes

The vision for universal themes is that a user could create a site using WordPress without the Site Editor enabled. Then, when the Site Editor is more mature, users could switch to using that, with all the extra tools that Full Site Editing will bring. 

A universal theme would work in both editing modes.  A user should be able to build a site in classic mode and switch to FSE mode when the Site Editor is more mature or when they are ready to try all the extra tools that Full Site Editing will bring. Changes to a theme in classic mode should be reflected when I enable the Site Editor.

Side note: It is not expected that users would toggle between these two modes. The plan will be for everyone to migrate to the Site Editor at some point. The intention of universal themes is to allow people to easily migrate from classic to FSE, not to encourage switching between them.

Future-proof

We that know that the Site Editor is coming. Building themes in this way will allow users to transition from classic themes to block themes when they are ready without requiring them to switch themes.

To achieve this we need to consider several aspects of themes:

Templates

In classic themes, templates live in the root directory and, by convention, `template-parts`. In block themes they live in `block-templates` and, by convention, `block-template-parts`. We could build templates for both classic and block themes and put them in the respective directories but the problem with this approach is that if users make changes to their templates when in classic mode they will not be reflected if they switch to the Site Editor.

To use the same templates when in classic and FSE mode we can put our templates in the `block-template-parts` directory. We can include them in our block templates in our template file like this:

block-templates/page.html:

<!-- wp:template-part {"slug":"page"} -->

For classic templates we can include the same file using `gutenberg_block_template_part`, which will execute `do_blocks` on this template:

/page.php:

echo gutenberg_block_template_part( 'page' );

This approach means that users can switch from classic to FSE mode without losing their changes.

Classic themes use `wp_nav_menu` to render theme navigation elements, which can be customised in the Dashboard, or in the Customizer. On the other hand, Block themes rely on the Navigation block to display their navigation. A recent change to the Navigation block means that we can connect these interfaces together:

By passing the navigation block an `__unstableLocation` attribute with the location of the classic menu, we can display classic menus inside the Navigation block:

<!-- wp:navigation {"__unstableLocation":"primary"} --><!-- /wp:navigation -->

This allows us to edit menus in the Customizer and the Dashboard when in classic mode, and in the Navigation block when in FSE mode.

Sidenote: A short-coming of this approach is that once the navigation has been edited in FSE mode, it will not be possible to edit it in classic mode.

Customization

In classic mode, the Customizer is the main tool for editing theme settings. Aside from Menus (see above), by default the Customizer allows users to edit Site Identity and Homepage Settings. These are WordPress settings that are editable elsewhere in the Dashboard, and are also available to block themes. The exception to this is “Additional CSS” which is not editable when the Site Editor is enabled. The hope is that the Site Editor will allow users to edit their site directly so that they won’t need to use additional CSS.

Often themes add more customisation options – for example colors and fonts. Global Styles offers some of the same customisations. Using the Global Styles API it is possible to make changes to Global Styles in the Customizer. This would allow users to customise their site using both the Customizer and Global Styles. We’ve been playing with this idea in this PR: Quadrat: Add color customization.

Opting in and out of the Site Editor

One unresolved challenge for universal themes is how to opt-in users to the Site Editor. At present the Site Editor is enabled for all block themes, which includes universal themes (if your theme has a file in the location `block-templates/index.html` it will be treated as block theme).

To be able to launch universal themes before the Site Editor is ready, we will need a mechanism to temporarily disable it. There is more discussion on this issue.

What’s next?

At the moment universal themes are just an idea; there are still many unresolved questions about how we could achieve this vision. For an example of a theme that tries to take a universal approach see Quadrat.

Look out for more posts about this idea as we keep experimenting with it.

Using Blockbase for a theme experiment

A glitchy theme, built with Blockbase.

Last week I spent a little time putting Blockbase to the test. I had some explorations into warping text and images using CSS and SVG filters gathering dust, and I thought it would be fun to explore pulling those into a highly-opinionated block theme.

In the past when I’ve done a theme experiment like this, I’ve generally started with something like the emptytheme generator in the WordPress theme-experiments repository. This provides you with just the required files for building a block theme, so it’s a good minimal way to get started.

This time around, I used Blockbase. While it doesn’t yet include a quick generator script like emptytheme does, there is one in the works. In lieu of that, I just created a child theme like I normally would: by adding style.css, functions.php, and index.php files. I also copied over the child-theme.json file from the in-progress Quadrat theme, since I knew that would get me started.

My work in child-theme.json was very brief — I just changed a few variables and used Blockbase’s compiler script once. Then I copied and pasted over the block style effects from the plugin mentioned above.

Once that was all in place, I jumped into custom templating. I created just two templates, plus a custom header that featured a video loop of me waving at the camera (but filtered into oblivion using the tools at photomosh.com). I used a “Warped and Stretched Photocopy” block style on the header’s text, and “Photocopy” style on the featured images. Combined together, this created a highly stylized look and feel, reminiscent of (for better or for worse) the old days of Flash animations:

This all worked pretty well in the editor too! Due to a combination of Gutenberg limitations and browser bugs, I ran into an issue getting my SVG filters loaded into the Site Editor’s iFrame, but aside from that, things looked just like the frontend:

The filters did work great in the post editor though, so I can show you how that’s supposed to work by loading the header there:

In the end, the filters bug is not really a fault of the theme, and something I’m sure I could resolve if I choose to devote some more time to this exploration.

The theme is obviously a little over-the-top, but that was really the point of the experiment! I’m amazed I was able to fold my earlier block styles work into such a distinctive, full-featured theme with minimal effort.

Overall, I found that the benefit to using Blockbase was peace of mind. Compared to starting fresh or using emptytheme, Blockbase ensured that I had a fully-functional block theme immediately. It already contained extra templates for pages like 404 and search, and it was full of little CSS fixes for things that full-site editing just doesn’t quite support yet.

This eliminated a lot of extra busywork, and allowed me to dive right in and focus on the theme-building aspect that’s most exciting for me: the theme’s design and creativity.

The code for the theme is over here in case anyone would like to poke around:

https://github.com/Automattic/themes/tree/try/glitchy-theme-experiment/glitchy

I look forward to seeing Blockbase spark the creation of many more themes!

Blockbase: A parent theme for block themes

Phase 2 of Gutenberg introduces Full Site Editing to WordPress; to make this possible, we need a new way of building themes – using blocks.

How do block themes work?

Block themes use templates made entirely of blocks. The layout is configured using a combination of theme.json and CSS. The settings in theme.json are used to generate CSS – this is part of the Global Styles feature. The theme CSS is added after the theme.json CSS and together these rules define the layout for a theme. If you’re just getting started with block themes, this guide should help.

Can I style my whole theme with Global Styles?

Global Style allows us to set styles for some aspects of the theme, but many common customisations are not yet available. We are actively helping to add more customisations to Global Styles, but in the meantime we have been working on a mechanism to define a lot more theme styles in a custom section of theme.json, until they are available in Global Styles.

The result of this work is a new theme called Blockbase, loosely based on the classic theme Blank Canvas. This block theme attempts to make all the common theme styles configurable in theme.json, and provides the CSS needed to make them work until the blocks themselves support these settings. As more of these configurations are added to Global Styles, we will remove the corresponding CSS from Blockbase.

Can Blockbase be used to build more block themes?

We are currently using Blockbase as a parent theme for all of our block themes; in time we hope that it won’t be needed. This means that child themes only need to define their settings in a theme.json file, and the parent theme CSS will adjust to these settings. This approach gives us an agreed standard when configuring block styles. It also will make it trivial to move to the Global Styles implementation when that becomes available in core.

Blockbase is intended to be a representation of all the theme style settings that we believe should eventually live in Global Styles and be configurable by users. Some themes need customizations beyond what would be possible with Global Styles. These more unique styles continue to be defined in the theme CSS file.

How it works

Style configurations live in the “styles” section of theme.json. Rules can be defined for both “blocks” and “elements”, and these will be interpreted by Global Styles and generate the appropriate CSS.

The theme.json file also contains a section for “custom” configurations, inside the “settings” property. Settings defined in “custom” are output by Global Styles as CSS variables. These variables are used by the theme CSS files to style blocks and other elements.

Child themes of Blockbase are able to redefine these CSS variables by setting different values in its theme.json. The child theme inherits the Blockbase CSS, but with the new CSS variables defined in theme.json.

To avoid a child theme needing to redefine every value in the theme.json file, child themes can create a child-theme.json file and a script will generate a theme.json file, taking the defaults from Blockbase and updating it with the new values from the child theme.

This mechanism will be particularly useful as more customizations are added to Global Styles; in many cases it will only be necessary to update Blockbase itself and rebuild each child theme, to update the theme.json files. You can find out more about this in the theme’s readme file.

Code size

Aside from the benefits outlined above, we have also found that this approach to building themes has resulted in a drastic reduction in the amount of code we need to write for both the parent theme and any child themes. As much as possible we rely on the styles that come with Gutenberg, and only add extra rules where necessary. Blockbase CSS is, at the time of writing about 1000 lines of code, whereas Seedlet CSS is over 4000.

As more of these customizations are added to Global Styles, we will be able to remove the corresponding CSS from Blockbase, so we anticipate the size of the theme CSS to reduce over time.

How Can I Use This?

Blockbase is available on the Automattic themes repo. If there is interest from others in using this approach to build themes we can investigate making it available as an npm package for others to use.

Getting Started with Block Themes: Patterns

Block Patterns, or simply patterns, enable theme developers to create custom blocks that are compositions of blocks provided by the standard block library, and if desired, with additional design flourishes. For example, Twenty Twenty One includes support for blocks designed with overlapping images and text, among others. In the blocks version of Twenty Twenty One, these will be registered as patterns within the theme.

Repeatable design patterns

Unlike templates, patterns are defined in PHP in a way that might be more familiar to experienced theme developers. We can define them in the functions.php file of our theme, or a file that is included there.

First up, as a matter of good practice, we register a category for our patterns using the register_block_pattern_category function. By categorising our patterns, we can separate them from other patterns such as those registered by WordPress core, and other third-party plugins:

register_block_pattern_category(
    'theme_blocks',
        array( 'label' => esc_html__( 'Theme Blocks', 'theme-blocks' ) )
);

Now we can start adding our patterns with the `register_block_pattern` function. The parameters for this function are the pattern name as a string, and an array of properties to be associated with the pattern. This array comprises a title, content, description, categories, keywords and viewport width. Putting this together, a simple pattern can be registered like this:

register_block_pattern(
    'theme-blocks/pattern-name',
        array(
            'title'         => esc_html__( 'Pattern Title', 'theme-blocks' ),
                'categories'    => array( 'theme-blocks' ),
                'viewportWidth' => 1024,
                'description'   => esc_html_x( 'A description of what is in the pattern', 'Block pattern description', 'theme-blocks' ),
                'content'       => '<!-- wp:columns ... -->'
        )
);

Most of what we’re doing here is self-explanatory, however the content property may look less familiar. This property contains the raw HTML content for the pattern. What we add here follows the same convention as template parts.

Getting real

It’s easier to think about what this contains if we work with a real pattern, so let’s take Twenty Twenty One’s Overlapping Images pattern. The content looks like this:

<!-- wp:columns {"verticalAlignment":"center","align":"wide","className":"is-style-twentytwentyone-columns-overlap"} -->
    <div class="wp-block-columns alignwide are-vertically-aligned-center is-style-twentytwentyone-columns-overlap">
            <!-- wp:column {"verticalAlignment":"center"} -->
                <div class="wp-block-column is-vertically-aligned-center">
                            <!-- wp:image {"align":"full","sizeSlug":"full"} -->
                                    <figure class="wp-block-image alignfull size-full">
                                            <img src="' . esc_url( get_template_directory_uri() ) . '/assets/images/roses-tremieres-hollyhocks-1884.jpg" alt="' . esc_attr__( '“Roses Tremieres” by Berthe Morisot', 'tt1-blocks' ) . '"/>
                                        </figure>
                                <!-- /wp:image -->
                                <!-- wp:spacer -->
                                    <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
                                <!-- /wp:spacer -->
                                <!-- wp:image {"align":"full","sizeSlug":"full"} -->
                                    <figure class="wp-block-image alignfull size-full">
                                            <img src="' . esc_url( get_template_directory_uri() ) . '/assets/images/in-the-bois-de-boulogne.jpg" alt="' . esc_attr__( '“In the Bois de Boulogne” by Berthe Morisot', 'tt1-blocks' ) . '"/>
                                        </figure>
                                <!-- /wp:image -->
                        </div>
                <!-- /wp:column -->
                <!-- wp:column {"verticalAlignment":"center"} -->
                    <div class="wp-block-column is-vertically-aligned-center">
                            <!-- wp:spacer -->
                            <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
                            <!-- /wp:spacer -->
                            <!-- wp:image {"align":"full",sizeSlug":"full"} -->
                                <figure class="wp-block-image alignfull size-full">
                                        <img src="' . esc_url( get_template_directory_uri() ) . '/assets/images/young-woman-in-mauve.jpg" alt="' . esc_attr__( '“Young Woman in Mauve” by Berthe Morisot', 'tt1-blocks' ) . '"/>
                                    </figure>
                            <!-- /wp:image -->
                    </div>
            <!-- /wp:column -->
    </div>
<!-- /wp:columns -->

To ease readability, we have added line breaks and indentation, but it’s worth noting that as this is ultimately just a string, when we come to registering our pattern, we can paste it in as a long line of text.

What we can see in this block is a mix of regular HTML, with the Block Editor’s pseudo HTML expressed as comments. Boiling it down, this markup contains two columns, with each one containing an image and some stylistic spacing. The images used here are just placeholders that can be modified by users in the editor, but it’s worth noting that any placeholder images used in a pattern must also be included in the theme assets.

You may note that in the markup above, it’s not entirely clear where the magic that makes these columns overlap occurs. This is achieved via a block style, and applied using the is-style-twentytwentyone-columns-overlap class.

Putting it all together

With all of this in place, here’s how we can now interact with our pattern in the site editor.

As you can see, we can find it by searching for “overlap” in the block editor. We can also browse all of our patterns in the block browser which is accessed by clicking “browse all” when selecting a block in the inline editor.

Why should I use patterns?

Hopefully this has helped you gain some understanding of what patterns are and how they work. Don’t worry if you’re still a little confused. There’s a lot to take in here and it’s something that makes more sense once you start making patterns. However, you may still be wondering why we’re talking about this and what the advantages are of using patterns.

Patterns are very helpful when users are trying to create more advanced layouts that have a greater sense of art direction than WordPress has traditionally provided. They’re a great way of breaking the monotony that can set in with long-form content, as well as helping users break the sense of creative block that is often felt when confronted with a blank page. As you can see in the patterns included with Twenty Twenty One, users have easy access to more versatile and visually interesting ways of presenting their content.

Next steps

To help consolidate your understanding, check out the full implementation of Twenty Twenty One’s patterns in the experimental block-based version of the theme.

Getting Started with Block Themes: Global Styles

Global Styles is a new mechanism for a theme to define a site’s styles. An important goal of Global Styles is to make it easier for users to change how their site looks without having to know or write any CSS.  These theme styles are defined via a json configuration file.  Importantly, it opens the way for users to modify those settings themselves in the Global Style Editor. 

Here you can find an empty theme JSON file to check out.  There’s a “Global” object with a “settings” block and a “styles” block.  You’ll find plenty of details about this JSON file here in the Gutenberg docs. Remember, work is ongoing so those details will change and grow. Q has built this very handy tool to get started with some generated JSON and get a head start on building your own theme.

Let’s take a look at some of those settings.

Global Settings

An important thing that we define at the global level is the palette of a theme. These are the colors that will be used throughout.
This will be in our settings portion of the JSON in the global.settings.color.palette collection and looks like this.

{“global”: { “settings”: {
	"color": {
		"palette": [
			{
				"slug": "blue",
				"color": "#0000FF",
				"name": "Blue"
			}
			…

With that defined there’s now a CSS variable –wp–preset–color–blue to be used throughout the theme.  And since it’s defined at the :root level you can use it throughout your theme’s JSON and CSS.  

This portion of the docs outlines the details of how that gets translated from JSON objects to CSS variable names. It follows the –wp-preset–{category}–{slug} pattern. 

And all of the colors in that palette are now at the disposal of users to apply across any block that supports colors.

A quick note regarding naming conventions:

It creates an easier time for users when switching themes if the palette names are descriptive of what they ARE rather than what they are FOR.  For instance “light-blue” or “canary-yellow” is more helpful than “secondary” or “accent”. 

This is because when users switch themes, if a palette color that they have chosen has the same name in the new theme then that palette color will still be used.   So if they picked a blue color, but it was labeled “secondary” and the new theme has a “secondary” color that is actually orange then suddenly something is orange that used to be blue and the poor user is very confused as to why. 

Whereas if they choose a color labeled “light-blue” and switch to another theme where there is also a “light-blue” palette color (even if it is a slightly different shade of blue) then their choice of color holds and is less likely to be confused about the color of their elements.

This also holds true for font size names: ‘small’ and ‘normal’ are a cleaner choice than ‘primary’ and ‘secondary’.

Global Styles

With this palette in hand you can associate those colors to your site at the global level or per-block to get the theme styled right.  Looking toward the styles portion of the configuration we can adjust what colors we use for things like the background.  This setting for global.styles.color.background shows us how to leverage the color value we just created:

{“global”:{
	"styles": {
	    	"color": {
			"background": "var(--wp--preset--color--blue)"
		}
	}
	…

There are a lot more important things like typography that we can use these global styles and settings for (and even some custom values) and I’ll mention more below. But for now let’s go a little deeper…

Block Styles

Now we can get extra fancy.  The above showed us settings at a global level.  But using JSON we can now also assign these styles to blocks, simply by targeting the block’s ‘context’ instead of ‘global’ context:

…
“core/heading/h1”:{
	"styles": {
	    	"color": {
			"background": "var(--wp--preset--color--blue)"
		}
	}
	…

These values are rendered into CSS which applies that style to every h1 element.

h1 {
	background-color: var(--wp--preset--color--blue);
}

Though for some blocks these values are rendered into a class which is applied to blocks of that type.  For instance, Gutenberg turns the configuration for a “core/site-title” into:

.wp-block-site-title {
	background-color: var(--wp--preset--color--blue);
}

And should a user want to customize that further…

User Block Styles with the Global Style Editor

And finally the Global Style Editor in the Full Site Editor can be used to customize aspects of a block at the site level.  These values will supersede whatever is set in the theme’s JSON. 

Here a user is changing the Site Title’s background style via the Global Styles Editor.

Typography

Just like colors, defining typography for a theme has moved from the realm of PHP to some simple configuration.

Adding some objects to global.settings.typography.fontSizes looks like this:

{“global”: { “settings”: { “typography”: {
	"fontSizes": [
		{
			"slug": "small",
			"size": "15px",
			"name": "Small"
		},
	]
	…

And just like colors, defining the font sizes for the theme in this way will give users access to these same values in the editor. This makes it easier for them to reuse the sizes the theme designer defines. 

Font families can be defined in the same way:

{“global”: { “settings”: { “typography”: {
	"fontFamilies": [
		{
			"fontFamily": "sans-serif",
			"slug": "noserifsplease",
			"name": "Sans"
		}
	]
	…

Of course for non-system fonts you’ll also need to load the fonts.  This can still be done in the function.php file with wp_enqueue_style and should seem familiar.

…
wp_enqueue_style( 'mytheme-fonts', 'https://url/for/font-face/definitions' , array(), null );
…

Or include the font face in your style.css

@font-face {
  font-family: 'Epilogue';
  font-style: normal;
  font-weight: 300;
  src: url(https://url/for/font-file.woff) format('woff');
}

Now that the font is loaded it can be used in the theme.json file:

{“global”: { “settings”: { “typography”: {
	"fontFamilies": [
		{
			"fontFamily": "\”Epilogue\”, sans-serif",
			"slug": "epilogue",
			"name": "Epilogue"
		}
	]
	…

And now these font values can be leveraged either at the global level or at the block level in your configuration, crafting the look and style of the theme:

{“global”:{ 
	"styles": { 
		"typography": {
			"fontSize": "var(--wp--preset--font-size--normal)"
			“fontFamily”: “Epilogue”
			…

…
“core/site-title”:{ 
	"styles": {
		"typography": {
			"fontSize": "var(--wp--preset--font-size--normal)"
			“fontFamily”: “Epilogue”
			…

CSS

Not all styles can be expressed in the theme JSON. In time we hope that all common styles will be available, but there will always be some things that will only live in CSS (like animations). 

The theme’s style.css file will continue to be available as a way to express the style of a block-based theme.  Blocks can continue to be styled in CSS with classes.  But now you can use all of the swatches defined in your theme JSON throughout.  You can even define custom values like a global vertical spacer value.

Theme JSON
{“global”: { “settings”: { “custom”: {
	“spacing”: {
		“vertical”: “20px”
		…
Theme CSS
.wp-block-of-some-kind {
	padding-top: var(--wp--custom--spacing--vertical);
	…

Buy Why?

Defining styles in this way has some important advantages.  

JSON configuration is more accessible than writing PHP code and CSS.  There’s less to understand, less to type and less to potentially mess up.  This doesn’t “re-invent CSS as JSON” and the concepts of CSS certainly don’t go away because of this new tooling.  Nor will PHP.  But key concepts present in every WordPress theme can be expressed simply and in ways that can be leveraged in more ways than CSS alone.  This will make Theme development a simpler and faster process.

But perhaps one of the most important aspects of this new Global Styles system is the power it puts in the hands of people USING a Theme.  By using a Theme as a starting place and providing the tools to tweak things to suit their needs, without custom CSS and in a visually clear way is incredibly powerful.  This makes ALL themes leveraging these tools immediately more powerful.

Getting Started with Block Themes: Templates

Full Site Editing provides a new and exciting way to build themes, compared to how we created themes in the past. If you are new to this, there’s nothing to worry about, it’s simply a different way to create themes, leveraging the existing template hierarchy we all know and love.

List of templates under Appearance » Themes.

A block-based theme can be customized from the Site Editor by making use of templates and template parts. A template is analogous to a template file in WordPress, following the same naming convention from the template hierarchy. You can edit templates from the Site Editor, or in the Block Editor under Appearance » Templates.

A template can contain individual blocks, or it can use reusable structural template parts, such as header, footer, and sidebar, for example. Template parts are not limited to the common reusable areas of a site, they can be virtually anything: a contact form, a call to action banner, or anything you want it to be.

When you update a template part from within a template, the template part is automatically updated everywhere (on all templates that use it). This works in the same way as reusable blocks, streamlining the process of working with templates.

The complexity of your theme will determine how many templates you need to create. You have freedom to use the Site Editor in any way you like, but for most themes you’ll want to create some template parts. 

Templates live in the theme code, inside the block-templates/ directory, as individual HTML files. Template Parts are stored in the block-template-parts/ directory.  Both templates and template parts are automatically loaded when WordPress loads, and are readily available in the Site Editor and Block Editor.

Source code of a template HTML file.

Templates and template parts can be stored as data, just like posts or pages. You can save a template and design your site’s behavior directly from the Site Editor, without having to provide the template HTML file in the first place.

Block templates

In the classic way of theming, we usually have functions that give us the different parts that make up a post, such as the_title(), the_content(), and so on. Block themes give us the same features using blocks directly!

For this purpose, some blocks have been made to be used with block-based themes. For example, you’ll most likely use the Site Title block in your site’s header while your single post template will most likely include a Post Title and a Post Content block.

As we’re still early in the process, the number of blocks is relatively small, but more will be added as the project evolves. For more information on this, you can refer to the official block themes reference.

When you build your template there are some important blocks you’ll want to use, which are covered in the sections below.

Site Level blocks

These blocks will be the same on every page – they get their content from the database. If you change the Site Title in this block, it updates everywhere on the site:

  • Site Title
  • Site Tagline
  • Site Logo

Navigation

Navigation is one of the most important parts of a website. The navigation block allows you to select menus you have previously created, or create new ones directly from the Site Editor.

If you have a header template part, this is a good place to add the Navigation block.

The navigation block in use.

Query block

The Query Block is different from other blocks; its content changes depending on the context in which it’s used. 

On the front page, the Query block will show your latest posts (by default). On an archive / category / tag page, the block will show the relevant content for that page. 

There are several blocks you can add inside the Query Block:

  • Post Title
  • Post Content
  • Post author
  • Post Comments
  • Post Comments Count
  • Post Comments Form
  • Post Date
  • Post Excerpt

You can combine these dynamic blocks with other blocks, for example columns, to change the layout of your posts and pages to your liking.

Dynamic blocks are blocks that use placeholders in the Site Editor, but will actually read information from the database when the blocks are rendered into the page. Therefore, it’s completely normal to not see the actual content when you are editing or inserting the block,  it will appear when the block is properly rendered.

Saving templates

After you have created all the templates and template parts in the Site Editor, you can save your templates to their corresponding HTML files. These can then be included in the theme.

Templates can be exported from the Site Editor, by clicking on the three dots button on the top-right hand side, and then clicking on Export.

Exporting a template from the Site Editor.

After exporting, you get a ZIP file downloaded to your computer, with all templates and template parts. You can extract the ZIP archive and copy the block-templates/ and block-template-parts/ directories into your theme and you’re good to go!

When the template files are bundled with the theme, they will automatically be loaded when WordPress starts. There is no need to import or create the templates, they are loaded directly!

Template loading order

As mentioned above, if a template is saved into the theme code, it will be automatically loaded on startup. You can make edits to the template from the Site Editor. 

Once the template is saved in the Site Editor, the template file will no longer be used. This means that changes saved from the Site Editor take precedence over the content stored in the template HTML files.

Have in mind, that if you make edits to any of the templates provided by the theme, the template you saved with your changes will be used instead of the template on disk. This means, if the theme ships an updated version of the template, you will not be able to see the changes unless you delete the templates from Appearance » Templates.

Up next, we’ll be talking about Global Styles, stay tuned!

Getting Started with Block Themes

The rationale

With Full Site Editing on the horizon for WordPress, Theme creators need to start to learn how to make themes in a different way. Full Site Editing is sea change in the way that themes work.

When Themes were first added to WordPress, they were simple; just a few template files and some CSS. Over time, as users demanded more from WordPress, themes have grown to contain much of the visual functionality of the site. This has enabled WordPress to be extended as far as your dreams allow, and has contributed to the popularity of WordPress today.

This approach for themes has brought some challenges with it. With so much functionality baked into a theme, changing themes becomes a difficult thing to do. Not only will you lose some of the functionality of your site, you probably have to learn a new UI, since every theme works differently.

The Full Site Editing project aims to address these concerns by moving a lot of this functionality into the Block Editor. This will simplify Themes again so that they will become more like the initial implementation; a presentation layer over the top of the content.

One major benefit of this approach is that users will be able to edit parts of their site that before were only editable with code.

Full Site Editing is several projects combining to create fundamental changes to the way WordPress works.

The Block Editor

Gutenberg – the name of the plugin containing the Block Editor

Fundamental to Block Themes is the Block Editor. Allowing users to express all their content as a Block brings us several benefits:

  • A consistent UI for creating/editing content
  • A reliable API for manipulating content
  • A transferable way to move content around

With this foundation Themes can lean much more heavily on the user’s content than they have before. For example, themes can provide a ready-made collection of blocks that users can insert (Block Patterns).

The Site Editor

The Site Editor allows users to edit templates in the same way that they already edit content blocks. Templates are blocks, so all the things that users are comfortable and familiar with in the Block Editor work the same way in the Site Editor. This allows users to manipulate their site content and layout in the same way as the Post and Page content. No longer will users have to learn different interfaces for different themes.

Preview of the empty site editor

Global Styles

Global Styles lets Themes express their design in a way which can be edited via the Block Editor and Site Editor. Rather than the design living in a CSS file, the most common settings will be defined in the editor itself, which gives the user the power to change them. This will enable users to modify the presentation of their site without writing any custom CSS.

Creating a Block Theme

The easiest way to start creating a new Block Theme is to use the empty theme template:

  1. Clone the theme-experiments repo:
    git clone https://github.com/WordPress/theme-experiments.git
  2. Run this php script to create a new Block Theme:
    php new-empty-theme.php

This provides the bare minimum needed to get started – in time, the amount of boilerplate code needed will shrink.

Next, install and activate the Gutenberg plugin – this will give you access to the features you’ll need for Full Site Editing.

Now when you enable your newly created Block Theme, the Side Editor will appear in the Dashboard sidebar, and the Customizer, Widgets and Menus will disappear.

Next Steps

To create your theme there are three areas to focus on:

  1. Templates
  2. Patterns
  3. Global Styles

We’ll be expanding on each of these in our upcoming posts. Stay tuned!

Creating a Block-based Landing Page Theme

Kjell Reigstad details how to build a single-page block-based theme.

The other day, my colleague Ian Stewart and I were discussing homepage templates, and this Carrd layout came up in conversation:

Layout from Carrd.co

Its two-column design is friendly and simple. It’s also drastically different than most WordPress themes we see these days — it doesn’t have a traditional header and footer, or even a menu for that matter. It really doesn’t look like a WordPress site (partly because it isn’t. 😄).

It does however look like a relatively simple pattern that could be built with Gutenberg blocks. With block-based themes on the horizon, Ian suggested I see how easy it would be to build a block-based theme featuring a similar homepage layout. I took him up on the challenge.

In about an hour, I had a fully functional version of the theme. Read on for details on how it all came together.


The Structure

The first thing I did was set up the basic theme files, and get them all hooked up to each other. Most of the theme files are more or less boilerplate — aside from a little CSS and some experimental-theme.json value changes, they aren’t going to change much from theme to theme. Here’s how that looked:

- assets
 	- (font files)
- block-templates
 	- index.html
- experimental-theme.json
- functions.php
- index.php
- style.css
- style-shared.css

HTML

  • block-templates/index.html was left empty to start with. As explained below, I populated this using Gutenberg.

JSON

PHP Files

  • index.php is empty, but needs to be there.
  • functions.php contains a standard function to enqueue the stylesheet. Aside from that, it just sets some theme options. Since this is an experimental block-based theme, I opted-in to just about all of the experimental options from the Block Editor handbook.

Stylesheets

  • style.css is enqueued only on the front-end. It includes a standard theme header docblock, plus barebones alignment styles, courtesy of Ari Stathopoulos. These styles just replicate the editor alignment rules from Gutenberg (standard, wide, and full) in the front-end. Hopefully Gutenberg can provide these styles one day, eliminating the need for this standalone CSS file.
  • style-shared.css houses the basic font and color rules, plus just a few theme-specific spacing overrides. This is loaded in both the editor and the front-end.

Building the Front Page Template

Once I had those files in place, I was ready to build the block template in block-templates/index.html.

First, I installed and activated my theme. With the empty HTML file created, I opened up the site editor, and was presented with a blank slate:

The Gutenberg site editor, with no content.

From here, I added a full-width columns block. On the left, I used a Cover block and uploaded my image. I used a columns block because I wanted to take advantage of two great Cover block features: its ability to take up the full height of the screen, and also its focal point picker which would ensure that the image is always centered on the model’s face.

The Gutenberg site editor with a cover block inserted into the left two thirds of the screen.

After that, I added a few center-aligned blocks to the right column: Site Title and Site Tagline blocks, a Button block, and a Social Links block:

The Gutenberg site editor with a Cover block on the left side, and a site title, description, button, and a set of social links on the right.

From there, I hit “Update Design” and used the Gutenberg plugin’s “Export” tool to download a zip file containing this template:

The "Export" option in the Gutenberg Plugin.

The resulting zip file included an index.html file containing the block markup I had just built. I replaced my empty block-templates/index.html file with this new one, and I had a fully functional single-page block-based theme! 🎉


Viewing the Final Result

The only thing left to do was check out the site in the front end. I was pleased with how similar everything looked to the editor, and how the whole layout was responsive by default.


This exercise made me truly excited about the future of theming. It took very little time to assemble the boilerplate necessary to get started, and I constructed most of the theme the editor itself. I imagine whole process will only get faster (and the boilerplate will be whittled down further) as full-site editing progresses.

The theme is available to test by visiting the Theme Experiments repository. There, you’ll find this as well as other themes like the new block-based version of Twenty Twenty-One.

For more in-depth details on building a block-based theme, visit the official tutorial in the Block Editor Handbook.

Creating a Block-based Theme Using Block Templates

This post outlines the steps I took to create a block-based theme version of Twenty Twenty. Thanks to Kjell Reigstad for helping develop the theme and write this post.

There’s been a lot of conversation around how theme development changes as Full Site Editing using Gutenberg becomes a reality. Block templates are an experimental feature of Gutenberg (as of 7.2.0), and using them to create block-based themes is in exploratory stages of development. 

A block-based theme is a WordPress theme with templates entirely composed of blocks so that in addition to the post content of the different post types (pages, posts, …), the block editor can also be used to edit all areas of the site: headers, footers, sidebars, etc.

Gutenberg Handbook

Before diving in, I’ll reiterate that much of how this works is subject to change. This spec is in a very early stage. I hope by writing this, your interest is piqued to learn more and contribute your own experiment to the WordPress theme experiments repository.

Step 1: Create the theme project

In its simplest state, a block based-theme’s structure should look something like this:

theme
|__ block-templates
    |__ index.html
|__ block-template-parts
    |__ header.html
    |__ footer.html
|__ functions.php
|__ index.php
|__ style.css

This is refreshingly simpler than most WordPress theme boilerplates. Here’s a quick overview what each file and directory does:

  • block-templates/: page templates that are composed of blocks. These follow the same template hierarchy as traditional themes.
    • index.html: the primary / fallback template to generate a post or page. (Analogous to index.php in traditional theme templates.)
  • block-template-parts/: the common collections of blocks to be used in block templates.
    • header.html: The global header, expressed in Gutenberg-generated HTML.
    • footer.html: The global footer, expressed in Gutenberg-generated HTML.
  • functions.php: This contains the usual theme setup and any other reusable functions.
  • index.php: This is actually just an empty file. You can technically remove it, but it’s a good habit to include an index file in every directory.
  • style.css: Contains your theme’s styles as usual.

Recreating Twenty Twenty as a block-based theme required adding a few extra stylesheets. Overall, I chose to add no extra page templates to keep the demo as understandable as possible.

Step 2: Create the block templates + block template parts

There were just two that needed to be totally rebuilt as blocks: the header and footer. The process for turning these areas into block templates was something along the lines of:

  1. Attempt to create the template parts in the block editor
    • This can be done in a draft post or page. If you’ve enabled the Full Site Editing experiment in the Gutenberg plugin, you’ll see a new admin panel area Appearance/Template Parts — an area where in the future I could create, store, and edit the block template parts in my theme.
  2. Style them as closely as possible using the editor
  3. Add block style variations + additional theme CSS to address any gaps that the core editor
    • Most of these styles were already present somewhere in the Twenty Twenty theme CSS, so I just needed to make minor modifications to assign them to the new blocks.

Step 3: Save those block templates + template parts as distinct files

When Full Site Editing is enabled via the Gutenberg > Experiments panel, Gutenberg will expect that your theme provides block templates, overriding the normal templating behavior:

Once I had my template parts designed and displaying properly, I would switch over to the Code Editor view, copy the markup generated, and paste the code into its respective file within my theme directory’s block-template-parts folder.

Edit: there’s an easier way to do this without switching to the code editor. You can select all blocks (Meta+A), copy (Meta+C), and paste into your text editor.

Step 4: Add theme starter content

In order for the theme to be populated with pages and content, I borrowed the official TwentyTwenty theme starter content. This step wasn’t 100% necessary, but a nice addition to have some content when someone activates the theme on a fresh WordPress site.

Demo

Here is the result: a site running the block-based Twenty Twenty.

Home page of the Twenty Twenty block based theme demo site.

Potential Block Improvements

Converting the header and footer to blocks helped me identify some functionality that would be nice to add to core blocks. Some of these are already in the works.

  • Navigation block
    • Control over how the menu is laid out and collapses in different viewports (#16829)
  • Columns Block
    • The ability control the padding and margins (#10730, #16660)
    • Adjusting the size of one column, the remaining columns don’t resize equally (#19515)

How is this better than what we have now?

The structural block-based theme changes are generally not obvious on the front end. The process of switching between the Code editor, a template file, and previewing the site to achieve the intended design was tedious. However, this is just an interim step before we’re hopefully able to create and edit our theme (and your entire site) via Gutenberg.

WordPress admin screen showing a block template part being edited.

The end benefit will become most apparent when the user can edit every piece of the page individually using Gutenberg. Being able to compose, manage, and reuse parts of your theme all within one visual interface is an exciting idea and one that’s close to reality.

The other exciting aspect of this process was that it required very little PHP — just a few block style variation declarations and standard theme support registration. Everything else is CSS and HTML generated by the editor. To me this feels like a step in the right direction, lowering the barriers to entry for folks that are new to theme development and WordPress.


I invite you to try it out; your comments and feedback are more than welcome. The source code for this theme is available on GitHub:

https://github.com/WordPress/theme-experiments/tree/master/twentytwenty-blocks

In that repository, you’ll find a handful of other block-based theme experiments: converted versions of Twenty Nineteen, the Gutenberg Starter Theme, and a theme called Parisienne. Each contains instructions for installation and activation.

By the way, the theme-experiments repository is open for PRs! I’d love to see more people creating and testing themes that use this method: that’s the only way it’ll grow and improve.

Feel free to ask questions in the comments or in the repository, and thanks for reading!