Block Locking Settings in WordPress 6.0

WordPress 6.0 makes it easier to lock blocks using the new controls modal. The release also includes two new settings to choose who can access this option and when.

BlockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. Editor

The new canLockBlocks setting can disable the feature globally or conditionally. Example:

add_filter(
	'block_editor_settings_all',
	function( $settings, $context ) {
		// Allow for the Editor role and above - https://wordpress.org/support/article/roles-and-capabilities/.
		$settings['canLockBlocks'] = current_user_can( 'delete_others_posts' );

		// Only enable for specific user(s).
		$user = wp_get_current_user();
		if ( in_array( $user->user_email, [ 'user@example.com' ], true ) ) {
			$settings['canLockBlocks'] = false;
		}

		// Disable for posts/pages.
		if ( $context->post && $context->post->post_type === 'page' ) {
			$settings['canLockBlocks'] = false;
		}

		return $settings;
	},
	10,
	2
);

Blocks

The lock property allows hide controls on a block type level. Example:

{
	"apiVersion": 2,
	"supports": {
		"lock": false
	}
}

For more info see #39183.

An earlier post on this blogblog (versus network, site) covers, the Curated experiences with locking APIs & theme.json

#6-0, #dev-notes, #dev-notes-6-0

Updates to the @wordpress/create-block templating system

A powerful feature of the @wordpress/create-block package is the ability to create templates to allow customization of how a blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. is structured.

WordPress 6.0 introduces some new template variables to allow even more customization. Templates can now use the customScripts variable to create new entries in the scripts property of the package.json file and while it was already possible to define dependencies, it is now also possible to defined a list of development dependencies using the npmDevDependencies variable. In addition to these new template variables, the @wordpres/env package will automatically be added to the list of devDependences when the template uses the wpEnv template variable or if the —wp-env flag is passed as a command line argument.

For more info see #38535#39723, and #38530.

#6-0, #dev-notes, #dev-notes-6-0

Block Editor miscellaneous Dev Notes for WordPress 6.0

Updated 2022-05-07 with a table of content, two more dev notesdev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include a description of the change, the decision that led to this change, and a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase. and some formatting –bph

Table of Contents


Removed bottom margin on LineHeightControl component

Several UIUI User interface components currently ship with styles that give them bottom margins. This can make it hard to use them in arbitrary layouts, where you want different amounts of gap or margin between components.

To better suit modern layout needs, we will gradually deprecate these bottom margins. A deprecation will begin with an opt-in period where you can choose to apply the new margin-free styles on a given component instance. Eventually in a future version, the margins will be completely removed.

In WordPress 6.0, the bottom margin on the LineHeightControl component has been deprecated. To start opting into the new margin-free styles, set the __nextHasNoMarginBottom prop to true:

<LineHeightControl
  value={ lineHeight }
  onChange={ onChange }
  __nextHasNoMarginBottom={ true }
/>

For more info see #37160.

Props to @0mirka00 for writing this dev notedev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include a description of the change, the decision that led to this change, and a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase.. (top)

Unrecognized blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. preservation

We’ve started making strides in preserving unrecognized content in the editor, also called (sometimes incorrectly) “invalidinvalid A resolution on the bug tracker (and generally common in software development, sometimes also notabug) that indicates the ticket is not a bug, is a support request, or is generally invalid.” or “missing.” In situations where the editor is unable to validate a loaded block against its implementation we run into numerous cases where content has previously been lost or corrupted, notably when inner blocks are involved.

Currently, we’re on the journey to preserving that original unrecognized content but have many corners in the project to update before it’s finished. Notably, when loading posts in the editor or in the code view that content will be preserved as it was loaded. Surprisingly, this lets us do something we’ve never been able to do before: intentionally create certain kinds of broken blocks within the code editor, or modify and fix blocks in the code editor whose block implementation is missing.

Still on the list to update are smaller parts of the flow such as the array of confusing block resolution dialogs and operations as well as certain validation steps that currently fail but shouldn’t.

In short, if you’ve been frustrated by the editor breaking your posts as soon as you hit “save” then good news is coming in 6.0.

For more info see #38794, #38923, and #39523.

Props to @dmsnell for writing this dev note.(top)

Registration of Blocks from within Themes

Until WordPress 6.0, building blocks inside plugins was the only way possible if you wanted to use block.json. This remains to be the recommended way to build Custom blocks  going forward. Blocks add functionality and therefore should be built as plugins that stay active even when a new theme is enabled. 

There are however instances where the styling and functionality of a block is so tightly coupled with a theme that it doesn’t make sense to have a block active without a given theme. This is true when building custom solutions, and the blocks are site-specific and not used for other instances. Furthermore, from discussion with agency project managers and developers, it turns out that there are considerable deployment costs when separating comprehensive solutions.

Each implementation had to reinvent a way to register blocks within themes, as WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. wouldn’t allow for it. With 6.0 the registration of blocks using block.json from within a theme is now technically standardized. You can use the same register_block_type function as you would inside a pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party and all the assets that you may register in the block.json file like the editorScript, style, etc get enqueued correctly.

For more info see #55513.

Props to @fabiankaegy for writing this dev note.(top)

Comments blocks – Enable legacy Post Comments block

With WordPress 6.0, there is a new set of blocks to show the Comments of a post:

  • Comments Query Loop: An advanced block that displays post comments and allows for various layouts and configurations.
    • Comment Template: Contains the block elements used to display a comment, such as the title, date, author, avatarAvatar An avatar is an image or illustration that specifically refers to a character that represents an online user. It’s usually a square box that appears next to the user’s name. and more.
    • Comments Pagination: Displays next/previous links to paginated comments where this has been enabled in the comment settings in the WordPress adminadmin (and super admin)
      • Previous Page: Displays the link to the previous page of comments.
      • Page Numbers: Displays a list of page numbers for comments pagination.
      • Next Page: Displays the link to the next page of comments.

The legacy Post Comments block, which directly renders the comments.php file, has been deprecated and hidden. It will still work for themes currently using it, but it won’t appear in the inserter.

The new set of blocks provides almost the same functionalities with the benefit that the layout and styles can be customized from the Editor. However, if any user wants to re-enable the Post Comments legacy block, they can use the block registration filters and adapt it to their needs. For example, this piece of code shows the legacy block in the inserter again and removes the “deprecated” from the title:

function wporg_enable_post_comments_legacy_block( $metadata ) {
    if ( 'core/post-comments' === $metadata['name'] ) {
        $metadata['title'] = esc_html__( 'Post Comments', 'textdomain' );
	$metadata['supports']['inserter'] = true;
    }
    return $metadata;
}
add_filter( 'block_type_metadata', 'wporg_enable_post_comments_legacy_block' );

For more info see #34994.

Props to @SantosGuillamot and @annezazu for writing this dev note.(top)

In order to implement this the spacing of the Gallery images had to be changed from a right margin setting to the CSSCSS Cascading Style Sheets. gap property. Themes or plugins that use a right margin setting to manually adjust the Gallery image spacing may need to be updated to instead override the gap setting.

Default gap changed

The new block editor block gap support functionality has been used to implement this and this adds a default block gap of 0.5em. For some themes that don’t explicitly set this gap, the default will change from the previous 16px to 0.5em. If plugin or theme developers want to ensure that the 16px gap remains the following CSS can be added to the theme, or site custom CSS:

.wp-block-gallery {
	--wp--style--gallery-gap-default: 16px;
}

Gallery Image bottom margins removed

Some themes may have depended on the bottom margin set on the gallery images to provide a gap between two galleries. Because the gallery now uses the flex gap for spacing this bottom margin is no longer set. Themes that were relying on this unintended side effect of the image margins will need to add the following CSS in order to maintain a gap between galleries:

.wp-block-gallery {
	margin-top: 16px;
}

Gallery gutter CSS var deprecated

To keep the naming of the gap setting consistent the --gallery-block--gutter-size CSS var has been deprecated and replaced with --wp--style--gallery-gap-default--gallery-block--gutter-size will continue to work in release 6.0 and will be removed in 6.1.

Theme authors should be able to provide compatibility for WP 5.9 and 6.0+ with the following:

.wp-block-gallery {
        --gallery-block--gutter-size: var( --wp--custom--spacing--4 );
	--wp--style--gallery-gap-default: var( --wp--custom--spacing--4 );
}

For more info see #40008.

Props to @glendaviesnz for writing this dev note.(top)

New ancestor property in block.json

Block developers sometimes need to restrict where users can place their blocks. For that, developers already count on APIs like block.json‘s parent property or the allowedBlocks option of the useInnerBlocksProps hook that allowed developers to express some basic, direct parent-children relations between blocks.

Since WordPress 6.0, the ancestor property makes a block available inside the specified block types at any position of the ancestor block subtree. That allows, for example, to place a ‘Comment Content’ block inside a ‘Column’ block, as long as ‘Column’ is somewhere within a ‘Comment Template’ block. In comparison to the parent property, blocks that specify their ancestor can be placed anywhere in the subtree, while blocks with a specified parent need to be direct children.

This property admits an array of block types in string format, making the block require at least one of the types to be present as an ancestor.

{
    "$schema": "https://schemas.wp.org/trunk/block.json",
    "apiVersion": 2,
    "name": "core/comment-content",
    "ancestor": [ "core/comment-template" ],
    ...
}

Block developers can also combine parent with ancestor inside block.json and use them together to express more complex relations if needed. For example:

  • Parent [ 'A' ] and ancestor [ 'C' ] would work as ”parent A and ancestor C”.
  • Parent [ 'A', 'B' ] and ancestor [ 'C', 'D' ] would work as ”parent (A or B) and ancestor (C or D)”.

Note that there are some edge cases uncovered by this APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways., like blocks that would require two or more different ancestor types simultaneously.

For more info see #39894.

Props to @darerodz for writing this dev note. (top)

Changes to media object returned from the WordPress data module

A small change has been made to the way the media objects are retrieved using the data module. The “caption”, “title” and “description” properties are returned as strings when using the `wp.data.select(‘core’).getRawEntityRecord` selector or the `wp.coreData.useEntityProp` hook.

Before

const [ renderedTitle ] = useEntityProp( 'root', 'media', id )?.rendered;

After

const [ renderedTitle ] = useEntityProp( 'root', 'media', id );

Props to @youknowriad for writing the note.

Removed Deprecated APIs

Some low-impact APIs that were deprecated on WordPress 5.4 have now been removed:

  • getReferenceByDistinctEdits selector.
  • PreserveScrollInReorder component.
  • dropZoneUIOnly prop in the MediaPlaceholder component.
  • isDismissable prop in the Modal component.
  • wp.data.plugins.control data module.

You can find more details on the #38564 removing these APIs

Slated to be removed in WordPress 6.2

The APIs listed have been deprecated in WordPress 5.3 and were forwarded in the background to the new ones already. They will be entirely removed in WordPress 6.2.

OldNew
wp.editor.+[name]wp.blockEditor.+[name]
wp.data.dispatch( 'core/editor' ).+ namewp.data.dispatch( 'core/block-editor' ). + name
wp.data.select( 'core/editor' ).+ namewp.data.select( 'core/block-editor' ). + name
wp.components.ServerSideRenderwp.serverSideRender

More details and discussion on PR #37854

Props to @youknowriad for writing the note.(top)

#6-0, #dev-notes, #dev-notes-6-0

Page creation patterns in WordPress 6.0

When a user creates a page, the editor starts with an empty canvas. However, that experience may not be ideal, especially since there are often possible patterns the user can use when creating a page, e.g., an about page, a contact page, a team page, etc.

Starting with WordPress 6.0, offering a set of patterns that users can choose from to create their pages is possible. We added a modal that shows possible patterns that can be used on page creation:

The modal appears each time the user creates a new page when there are patterns on their website that declare support for the core/post-content blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. types. By default, WordPress 6.0 CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. does not include any of these patterns, so the modal will not appear without some of these post content patterns being added.

Any theme or pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party can register a pattern with core/post-content block support and make the modal with the patterns appear. Here we provide a sample pattern that appears in this model.

register_block_pattern(
	'my-plugin/about-page',
	array(
		'title'      => __( 'About page', 'my-plugin' ),
		'blockTypes' => array( 'core/post-content' ),
		'content'    => '<!-- wp:paragraph {"backgroundColor":"black","textColor":"white"} -->
		<p class="has-white-color has-black-background-color has-text-color has-background">Write you about page here, feel free to use any block</p>
		<!-- /wp:paragraph -->',
	)
);

To register the page patterns via the theme.jsonJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. file added the Body Types section to the php stub:

<?php
 /**
  * Title: Hello
  * Slug: my-theme/hello
  * Block Types: core/post-content
  * Categories: featured, text
  */
?>
<!-- wp:heading -->
  <h2>Hello</h2>
<!-- /wp:heading -->

More details on the auto-detection of patterns via .php files, are available in this Dev Notedev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include a description of the change, the decision that led to this change, and a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase.: New features for working with patterns and themes in WordPress 6.0

Completely disabling this functionality

By default, no modal appears because there are no post-content patterns unless a theme or plugin registers one.
If one wants to disable the modal even if there are plugins registering post-content patterns, it is possible to do so by removing the post-content block type from all patterns, as the following code sample does:

$patterns = WP_Block_Patterns_Registry::get_instance()->get_all_registered();
foreach ( $patterns as $pattern ) {
	if (
		! empty($pattern['blockTypes'] ) &&
		in_array('core/post-content', $pattern['blockTypes'] )
	) {
		unregister_block_pattern( $pattern['name'] );
		$pattern['blockTypes'] = array_diff( $pattern['blockTypes'], array( 'core/post-content' ) );
		register_block_pattern( $pattern['name'], $pattern );
	}
}

For more info see #40034.

#6-0, #dev-notes, #dev-notes-6-0

Global Styles variations in WordPress 6.0

Theme authors can now create multiple theme.jsonJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. variations and place them into their theme’s /styles folder. From there, users can switch between the various presets to something that suits them best.

Custom JSON files should follow the standard theme.json schema and their filename is going to be used as the variation’s label in the UIUI User interface (example blue.json).

Webfonts handler

A webfonts handler has been included in this release, allowing theme authors to include multiple font options within a single theme.json file or to offer vastly different styles by utilizing different font options in their multiple theme.json variations.

{
  "settings": {
      "typography": {
          "fontFamilies": []
      }
  }
}

Here’s a more robust example of how to implement this new option:

{
	"settings": {
		"typography": {
			"fontFamilies": [
				{
					"fontFamily": "-apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,Oxygen-Sans,Ubuntu,Cantarell,\"Helvetica Neue\",sans-serif",
					"name": "System Font",
					"slug": "system-font"
				},
				{
					"fontFamily": "\"Source Serif Pero\", serif",
					"name": "Source Serif Pero",
					"slug": "source-serif-pero",
					"fontFace": [
						{
							"fontFamily": "Source Serif Pero",
							"fontWeight": "200 900",
							"fontStyle": "normal",
							"fontStretch": "normal",
							"src": [ "file:./assets/fonts/SourceSerif4Variable-Roman.ttf.woff2" ]
						},
						{
							"fontFamily": "Source Serif Pero",
							"fontWeight": "200 900",
							"fontStyle": "italic",
							"fontStretch": "normal",
							"src": [ "file:./assets/fonts/SourceSerif4Variable-Italic.ttf.woff2" ]
						}
					]
				}
			]
		}
	}
}

Right now, there is only support for top level settings and the more granular option of defining fonts per blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. is not currently available. For further inspiration, theme authors can review the approach the default Twenty Twenty-Two theme has taken since it will ship with three style variations with different fonts for WordPress 6.0.

Notes

  1. The variations require using the version 2 of theme.json.
  2. Right now when a variation is applied its contents are still merged with the theme and core theme.json, but it’s not possible to override a single value in an array of items or merge arrays. For example adding a value in settings.color.palette would replace the entire palette.

For more info see #38124.

Props to @annezazu for collaborating on this note.

#6-0, #dev-notes, #dev-notes-6-0

Separator block: Updated to use block supports color settings

To allow the setting of a custom opacity for each blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience., the Separator block has been updated to use the block that supports color settings. The custom opacity can then be set using the alpha channel setting of the selected color.

The HMTL structure of the block is unchanged, and all the existing classes are still in place, and two additional classes have been added – .has-alpha-channel-opacity and .has-css-opacity

These new classes have been added to maintain the default 0.4 opacity for all existing blocks in both the editor and the frontend. The opacity for existing Separator blocks will only change if the block itself has its color setting changed. If theme authors have opted in to block styles with add_theme_support( 'wp-block-styles' ); and wish to maintain the default 0.4 opacity setting for both new and old blocks the following CSSCSS Cascading Style Sheets. can be added:

hr.wp-block-separator.has-alpha-channel-opacity {
	opacity: 0.4;
}

#6-0, #dev-notes, #dev-notes-6-0

Block markup updates for image, quote, list and group blocks

Image blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. alignments

Historically, the image block with left, right or center alignments used to have an extra div wrapper around the figure tagtag A directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.) to help with alignment styling.

<div class="wp-block-image alignleft"><figure><img src="someimage.jpg" alt="" width="100" height="100"/></figure></div>

In WordPress 6.0, for themes that support the layout feature, this wrapper has been removed. The markup becomes:

<figure class="wp-block-image alignleft"><img src="someimage.jpg" alt="" width="100" height="100"/></figure>

The new markup/behavior for alignment classes is consistent regardless of the block and regardless of the chosen alignment.

To minimize the impact of this change on the websites, this change is only effective for themes with a theme.jsonJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. file. These themes do support the “layout” feature which automatically provides the right styles for this new markup.

Quotes and lists

The blockquote, ul and ol tag names all now come with a default value for `box-sizing` equal to `border-box`. This change has been made as a bugbug A bug is an error or unexpected result. Performance improvements, code optimization, and are considered enhancements, not defects. After feature freeze, only bugs are dealt with, with regressions (adverse changes from the previous version) being the highest priority. fix for quote and list blocks using background colors or padding.

Group block stack variation

The new Stack block is a variation of the Group block, and can be thought of as a vertical variant of the Row block. It’s a flex container, meaning it has access to content justifications and block spacing. If combined with the Row block and its ability to optionally wrap onto new lines, it can enable basic responsive behaviors, such as two columns that stack to a single column on smaller displays.

Removal of data-align div wrappers

In the editor and to support/style block alignments, the editor used to add wrapper divs to any block that had an alignment applied to it.
For themes that support the layout feature (with theme.json file), the div wrapper with the `data-align` attribute has been removed. The markup now matches exactly the frontend output.

#6-0, #dev-notes, #dev-notes-6-0

Support for handling resolution errors for Editor data module

WordPress 6.0 no longer ignores the exceptions thrown by the resolvers.

In WordPress 5.9 and earlier, an exception thrown inside the resolver kept it in the resolving state forever. It never got marked as finished. In WordPress 6.0, the resolver state is set to error and the exception is re-thrown. This backwards compatibility-breaking change affects both resolvers from newly registered stores and the resolvers from the WordPress stores, e.g. the getEntityRecord resolver from the coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. store.

Example:

Let’s register an example store where the resolver always throws an error:

const temperatureStore = wp.data.createReduxStore( 'my-store', {
    selectors: {
        getTemperature: ( state ) => state.temperature
    },
    resolvers: {
        getTemperature: () => { throw new Error( 'Network error' ); }
    },
    reducer: () => ({}), // Bogus reducer for the example
} );
wp.data.registerStore( temperatureStore );

Using that resolver has different results in different WordPress versions:

In WordPress 5.9:

const promise = wp.data.resolveSelect( temperatureStore ).getTemperature();

Error handling is unsupported, so this promise never gets rejected nor resolved.

In WordPress 6.0:

const promise = wp.data.resolveSelect( temperatureStore ).getTemperature();

Error handling is now supported, so this promise gets rejected with Error( ‘Networknetwork (versus site, blog) error’ )

The error details may be retrieved using the hasLastResolutionFailed, getLastResolutionFailure, and `getResolutionState` metaMeta Meta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress.-selectors available on every registered store:

wp.data.select( temperatureStore ).hasResolutionFailed( 'getTemperature' );
// the above returns: true

wp.data.select( temperatureStore ).getResolutionError( 'getTemperature' );
// the above returns: Error( 'Network error' )

wp.data.select( temperatureStore ).getResolutionState( 'getTemperature' );
// the above returns: { "state": "error", "error": Error( 'Network error' ) }

The state returned by getResolutionState is one of: “resolving”, “finished”, “error”, undefined. The undefined indicates that the resolver hasn’t been triggered yet.

PRs #38669 #39317

#6-0, #dev-notes, #dev-notes-6-0

Theme export in WordPress 6.0

The “Export” feature in the Site Editor has been improved so that now you can export your whole theme, including all the edits you have made to your templates and styles. Previously the export function only gave you access to your template files. This change makes it possible to build a blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. theme using the site editor and easily share the zip file with anyone.

The Export process

The export process copies all files from the current theme into a zip file. Then it extracts the template changes that are stored in the database to files and adds them to the zip file. If these templates have the same names as those in the theme, they will be overwritten, so that the database version takes precedence. The same process happens for the theme.json file. There are three directories that are excluded from the export: .git, node_modules and vendor.

Unexpected changes

The export process may make a few unexpected changes to your templates and theme.jsonJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. files.

  1. The output of template files from the database will be sanitized for security reasons. You’re most likely to notice this with any CSSCSS Cascading Style Sheets. variables in your template files: e.g. --wp--custom--spacing--outer would become \u002d\u002dwp\u002d\u002dcustom\u002d\u002dspacing\u002d\u002douter.
  2. The properties in theme.json are now sorted alphabetically, so the first time you export you might notice some of the objects in your theme.json move position. This now gives us a standard order for these properties so in future it will be easy to know where everything should go.
  3. The schema may be updated – the export will update your theme.json schema to match the version of WordPress you are using, so if you theme was created with an older version of WordPress, the schema will be updated to match the version you are on.

How to submit a theme

Once you have your exported theme, you may need to make several changes before you can submit it to the theme repository.

  1. The screenshot will need to be updated, if you’ve made any visual changes to the homepage.
  2. You will have to add a changelog entry to the readme.txt file.
  3. You must update the version number of the theme in style.css.
  4. If this is a new theme, based on an existing theme, you will also need to update the name.
  5. If the theme doesn’t have a license file already you will need to add one.
  6. You will then need to rezip the theme with these changes.
  7. You can now submit the new zip file to https://wordpress.org/themes/getting-started/.

For more info see:

#6-0, #dev-notes, #dev-notes-6-0

New features for working with patterns and themes in WordPress 6.0

WordPress 6.0 brings three new features to Themes to offer site owners patterns. Register selected patterns from the public pattern directory, add theme patterns to a separate folder /patterns, and add patterns that can be offered to use when creating a new page. 

Pattern registration from Pattern Directory for themes

With WordPress 6.0 themes can easily register patterns from Pattern Directory through theme.json. To accomplish this, themes should use the new patterns top level key in theme.json.

Within this field, themes can list patterns to register from Pattern Directory. The patterns field is an array of pattern slugs from the Pattern Directory. Pattern slugs can be extracted by the url in single pattern view at the Pattern Directory. 

Example: This url https://wordpress.org/patterns/pattern/partner-logos the slug is partner-logos.

{
    "version": 2,
    "patterns": [ "short-text-surrounded-by-round-images", "partner-logos" ]
}

Noting that this field requires using the version 2 of theme.json.

The content creator will then find the respective Pattern in the inserter “Patterns” tab in the categories that match the categories from the Pattern Directory.

Place Patterns in the subfolder /patterns of your theme

Themes can now define blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. patterns as files in the /patterns folder:

devnotes-patterns-directory

Each pattern file consists of a set of pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party-style headers followed by the pattern’s actual source:

<?php
 /**
  * Title: Hello
  * Slug: my-theme/hello
  * Categories: featured, text
  */
?>
<!-- wp:heading -->
  <h2>Hello</h2>
<!-- /wp:heading -->

Motivation

While all themes benefit from this APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways., it is especially convenient for block themes, where conventional folders like templates, template-parts and now patterns reduce the role of functions.php as a control structure. This API also paves the way for any future theme-editing tools that integrate with the block editor.

Note that this is not a breaking change. Much like plugins, themes have been able to register block patterns since the introduction of register_block_pattern() in WordPress 5.5, and that interface is not expected to change.

Observations

  • For now, the only format supported for these files is PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher. While a simpler HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. format has been considered, PHP offers theme developers an escape hatch, should the pattern have any special content that dynamic blocks haven’t yet absorbed. For instance:
<img src="<?php echo esc_url( get_template_directory_uri() ); ?>/assets/hello.png">
  • As a general reminder, these PHP blocks are only run upon loading the block editor in order to compute the patterns. Once inserted into a post, patterns are static.

Supported fields

  • Title (required) (implicitly translatable)
  • Slug (required)
  • Description (implicitly translatable)
  • Viewport Width
  • Categories (comma-separated values)
  • Keywords (comma-separated values)
  • Block Types (comma-separated values)
  • Inserter (yes/no)

Props to @ntsekouras.

#6-0, #dev-notes, #dev-notes-6-0