Make WordPress Core

Keyboard Shortcuts | Hide comment threads

Block supports API updates for WordPress 5.8

Expanding on previously implemented block supports in WordPress 5.6 and 5.7, WordPress 5.8 introduces several new block supports flags and new options to customize your registered blocks.

New Supports

color._experimentalDuotone – Adding duotone support to your block is a new experimental feature. To test, set this property to a string that specifies the CSS selector where you want to apply duotone. For example, in your block metadata:

1
2
3
4
5
supports: {
    color: {
        _experimentalDuotone: '> .duotone-img'
    }
}

color.link – Support for link color was added, this mirrors the usage and support for color.text that was added in WP 5.6.

To use in your block, add the supports flag in the block metadata:

1
2
3
4
5
supports: {
    color: {
        link: true;
    }
}

You can define a default value, using attributes and it will also use the values set in theme.json if present. For example:

1
2
3
4
5
6
7
8
attributes: {
  style: {
      type: 'object',
      default: {
          color: {
              link: '#FF0000',
          }
      }

Related ticket: #31524

Stabilized Supports API

Two features that were experimental in WordPress 5.7 have been stabilized in WordPress 5.8

  • fontSize previously __experimentalFontSize
  • lineHeight previously __experimentalLineHeight

See Block Supports API documentation for usage details.

The spacing support was updated and expanded to work for server-side blocks, as well as adding granular support to configure spacing for sides (top, right, bottom, left) individually. For example:

1
2
3
4
5
6
supports: {
    spacing: {
        margin: true// Enable margin UI control.
        padding: true, // Enable padding UI control.
    }
}

The following example configures side support for just top and bottom:

1
2
3
4
5
6
supports: {
    spacing: {
        margin: [ 'top', 'bottom' ], // Enable margin for arbitrary sides.
        padding: true,               // Enable padding for all sides.
    }
}

The spacing supports can target specific blocks using theme.json, or it’s own attributes. For example, customizing the top and bottom margins for the core/separator block:

1
2
3
4
5
6
7
8
9
10
11
12
"styles": {
    "blocks": {
        "core/separator": {
            "spacing": {
                "margin": {
                    "top": "100px",
                    "bottom": "100px"
                }
            }
        }
    }
}

Props to @mkaz and @nosolosw for help with compiling this dev note.

Related PRs: #31808, #31332

Tags: #5.8 #dev-notes #gutenberg

Introducing theme.json in WordPress 5.8

WordPress 5.8 comes with a new mechanism to configure the editor that enables a finer-grained control and introduces the first step in managing styles for future WordPress releases.

Controlling settings globally and per block

The introduction of blocks has increased the number of settings agencies and developers may need control over. Having a central point of configuration aims to provide a more consistent and complete experience.

By creating a theme.json file in the theme’s top-level directory, themes can configure the existing editor settings (the font sizes preset, whether custom colors are enabled, etc.) as well as the new ones as they are introduced (the duotone preset, whether margin and padding controls are enabled, etc.).

This new mechanism aims to take over and consolidate all the various add_theme_support calls that were previously required for controlling the editor.

The example below shows how to disable custom colors for all blocks:

{
    "version": 1,
    "settings": {
        "color": {
            "custom": false
        }
    }
}

The addition of the theme.json file also provides a way for theme authors to control these settings on a per-block basis ― something that wasn’t possible before. The example below shows how to disable custom colors for all blocks but enable them for the paragraph block:

{
    "version": 1,
    "settings": {
        "color": {
            "custom": false
        },
        "blocks": {
            "core/paragraph": {
                "color": {
                    "custom": true
                }
            }
        }
    }
}

Top-level settings will apply to all blocks that support the relevant setting. However, block-level settings can also override the top-level settings for a specific block. Blocks are addressed by their block name and settings can be added for core as well as third-party blocks.

Note: to retain backward compatibility, the existing add_theme_support declarations from the theme are retrofitted in the proper categories for the top-level section. For example, if a theme uses add_theme_support('disable-custom-colors'), the result will be the same as setting settings.color.custom to false. If a setting is declared in theme.json that setting will take precedence over the values declared via add_theme_support.

See the specification document for a complete list of features and backcompatibility with add_theme_support.

Blocks can access theme settings with useSetting

Core blocks have been updated to respect the new settings coming from a theme via theme.json. For example, if a block supports a UI margin control but the theme has disabled margin across the board, the UI control will not be displayed in the editor.

Third-party blocks can also tap into this mechanism by using the useSetting React hook in its edit function:

import { useSetting } from '@wordpress/block-editor';
// Somewhere in the block's edit function.

const isEnabled = useSetting( 'spacing.margin' );

if ( ! isEnabled ) {
    return null;
} else {
    return <ToggleControl ... />
}

See the API docs for useSetting.

CSS classes for presets are automatically created and enqueued

Previously, themes had to declare presets for the editor and also enqueue the corresponding classes separately.

In the functions.php file, they’d do:

add_theme_support(
  'editor-color-palette',
  array(  /* define color presets, including translations */
) );

And then, in the style.css:

.has-<value>-color { /* ... */ }
.has-<value>-background-color { /* ... */ }
/* etc */

By using a theme.json, the theme only has to declare their presets. The engine will set up the translations and will take care of creating and enqueuing the corresponding styles to both the editor and the front-end:

{
    "version": 1,
    "settings": {
        "color": {
            "palette": [
                {
                    "name": "Color name",
                    "slug": "color-slug",
                    "color": "<color-value>"
                },
                {
                    "name": "...",
                    "slug": "...",
                    "color": "..."
                }
            ]
        }
    }
}

See the specification document for a list of classes generated by preset.

CSS Custom Properties

By phasing out IE11 support, many CSS features become available. One of these now available features is CSS Custom Properties. When a theme adds presets via theme.json, the engine will enqueue both classes and CSS Custom Properties for them.

The example below:

{
    "version": 1,
    "settings": {
        "color": {
            "palette": [
                {
                    "name": "Black",
                    "slug": "black",
                    "color": "#000000"
                },
                {
                    "name": "White",
                    "slug": "white",
                    "color": "#ffffff"
                }
            ]
        }
    }
}

will create this output in CSS:

/* One CSS Custom Property per preset value. */
body {
  --wp--preset--color--black: #000000;
  --wp--preset--color--white: #ffffff;
}

/* The corresponding classes for each preset value. */

.has-black-color { color: var(--wp--preset--color--black) !important; }
.has-black-background-color { background-color: var(--wp--preset--color--black) !important;  }

.has-white-color { color: var(--wp--preset--color--white) !important; }
.has-white-background-color { background-color: var(--wp--preset--color--white) !important;  }

See the specification document for more examples, how to add and use custom properties unrelated to presets, etc.

Managed styles for improved coordination

One of the struggles theme authors face is the conflicts that appear in an environment with core, theme, and user styles as well as the wide design area that comes with multiple blocks that can be combined indefinitely.

The theme.json file absorbs most of the common use cases for styling blocks with the goal of reducing the amount of CSS shipped to the browser, mitigating specificity wars, and providing current style info in the UI controls for users. This is the first step in having a mechanism that consolidates all the three origins of styles (core, theme, user) and that will become more important once users can provide global styles in later phases of the project.

In the example below, a theme provides styles for the top-level and a couple of blocks:

{
    "version": 1,
    "styles": {
        "color": {
            "text": "var(--wp--preset--color--primary)"
        },
        "blocks": {
            "core/paragraph": {
                "color": {
                    "text": "var(--wp--preset--color--secondary)"
                }
            },
            "core/group": {
                "color": {
                    "text": "var(--wp--preset--color--tertiary)"
                }
            }
        }
    }
}

It results in the following CSS output:

/* Top-level styles resolve to the body selector. */body {
  color: var(--wp--preset--color--primary );
}

/* Block styles resolve to the block selector. */
p {
  color: var(--wp--preset--color--secondary );
}
.wp-block-group {
  color: var(--wp--preset--color-tertiary );
}

Any block, both core and third-party, can be targeted by its name.

See the specification document for a complete list of supported styles.

Access to other features

There are some features that are enabled or disabled when a theme has support for a theme.json file:

  • The template editor is enabled.
  • The default layout and margin styles for themes are not enqueued and the new layout options are enabled instead (see related dev note for layout).
  • The inner div for the group block (wp-block-group__inner-container) is removed.
  • The default font-family styles for the editor are not enqueued.

#5-8 #dev-notes #gutenberg

What’s new in Gutenberg 10.9? (23 June)

Two weeks have passed since the last Gutenberg release, which means the time has come for a new version. Gutenberg 10.9 introduces rich URL previews for Link Control, the ability to expand/collapse nested blocks in List View, and a new name for the Query Loop block — Post Template. The release also includes enhancements and bug fixes for Widgets Editor.

Rich URL Previews

When clicking on links in the editor, it’s now possible to see a rich preview of a URL including site title, meta description, icon and image. This is the first feature to take advantage of the new `url-details` endpoint, the enhanced form of which was shipped in 10.8. Currently, rich previews are only enabled for links which point to external URLs and then only for rich text blocks that utilize the core link format library. In the near future however, we expect to extend this to provide previews of internal URLs and to roll out support to more areas of the software.

List View Enhancements

This release brings a new feature to the List View. It’s now possible to expand and collapse nested blocks, which helps users navigate complex block structures. For example, users can collapse the content in sibling columns to concentrate on that hierarchy level and expand a single column to focus on it.

A new home for the Block Manager

The Block Manager has been moved from the Tools menu, and is now integrated with the new Preferences modal under the Blocks section, consolidating all editor-related preferences in the same modal.

Block Manager preferences

Updated template creation modal

This modal has been polished, including an improved welcome guide, to make creating new templates a breeze.

Renamed Query and Query Loop blocks

With the Query and Query Loop blocks becoming stable and coming to WordPress 5.8, they have been renamed to increase clarity about their functionality. The Query Loop block has been renamed to Post Template to better represent its purpose within Query, whereas the Query block label now refers to it as Query Loop.

10.9

Enhancements

  • Components:
    • UnitControl: Reduce code duplication for defined units. (32731)
    • BoxControl: Add support for grouped directions (vertical and horizontal controls). (32610)
    • Notice: Added onDismiss option in createInfoNotice. (32338)
  • Block Library:
    • Latest Posts: Limit latest-post authors dropdown to users with published posts. (32662)
    • Calendar: Add loading and empty state. (31504)
    • Query Loop: Add helpful text to the block. (32694)
    • Query Loop: Rename QueryLoop to PostTemplate and change Query label. (32514)
    • Spacer: Try an alternate min-height fix. (32543)
    • Heading: Show all heading levels in toolbar group. (32483)
    • Post Terms: Add a CSS class to identify the taxonomy. (31832)
    • Legacy Widget: Move block to @wordpress/widgets. (32501)
  • Block Editor:
    • Enhance link control UI with rich URL previews. (31464)
    • List View: Allow expanding and collapsing of nested blocks. (32117)
    • Editor Breadcrumb: Add a rootLabelText prop. (32528)
    • Don’t hardcode CSS units. (32482)
    • Refactor LinkControl component to support React 17. (32552)
    • Remove snapshots from tests for LinkControl. (32592)
  • Block Support:
    • Update border support to allow non-pixel units. (31483)
  • Icons:
    • Add new icons. (32371)
    • Tweak people icon. (32354)
    • Expose trendingDown and trendindUp icons. (32124)
  • Template Editing Mode:
    • Update welcome guide language for the template editor. (32639)
    • Translate delete template confirmation message. (32647)
    • Disable renaming templates named by core; Display descriptions. (32636)
    • Update the template creation modal. (32427)
  • Post Editor:
    • Use the post type singular_name as the root Block Breadcrumb label. (32609)
    • Absorb block manager within blocks preferences. (32166)
  • Widget Editor:
    • Hide some settings from the “Options” menu on small screens. (32690)
    • Add Breadcrumbs Block. (32498)
    • Use button block appender in widget areas. (32580)
    • Add show block bread crumbs feature toggle to more menu. (32569)
    • Unhide the classic menu widget. (32431)

Bug Fixes

  • Block Library:
    • Image Block: Fix cover block exists check. (32666)
    • Embed: Fix embed to paragraph transform when caption has rich text formats. (32355)
    • Columns: Fix deprecation caused when adding a column. (32378)
    • Site Logo: Fix site-logo not getting removed on remove_theme_mod. (32370)
    • Social: Try to fix color inheritance for social links. (32625)
    • Social: Correctly position the link popover when List View is open. (32525)
    • Code: Try an experimentalSelector. (31742)
  • Block Editor:
    • RichText: Fix loss of list content when switching list types. (32432)
    • useBlockDropZone: Fix horizontal indicator. (32589)
    • Inserter: Fix insertion point displaying when there are no inserter items. (32576)
    • Drop indicator: Show around dragged block and show above selected block for file drop. (31896)
    • Fix vertical scroll in horizontal toolbar. (32655)
    • Fix block multi selection in nested blocks. (32536)
    • Fix block toolbar overlap with header. (32424)
  • Blocks:
    • Avoid keeping the same client ID when transforming blocks. (32453)
    • Allow themes to add inline styles for all blocks when using lazy styles loading. (32275)
  • Components:
    • RadioControl: Add hideLabelFromVision prop. (32414)
    • DatePicker: Fix crash when navigating between months. (31751)
    • Autocomplete: Prevent setting state for unmounted component. (32654)
  • Editor:
    • Make link UI rich previews target agnostic and fix unwanted preview for internal URLs. (32658)
  • Widget Editor:
    • Don’t delete a widget if it is moved to a different area. (32608)
    • Fix button spacing in header. (32585)
    • Decode HTML entities for name and description props. (32503)
    • Fix dirty state after adding new block. (32573)
    • Don’t add undo levels when editing records on save. (32572)
    • Save deleted and restored widgets. (32534)
    • Don’t show widgets in menu without theme support. (32420)
    • Fix inspector opening on click outside widget area. (32450)
    • Legacy Widget: Don’t display “No preview” when widget has image tags. (32605)
  • Post Editor:
    • Prevent locking users in saving state when saving meta boxes fails. (32485)
    • Edit Post: Add metaBoxUpdatesFailure action. (32623)
  • Full Site Editing
    • Only add skip-link for block themes & templates on the frontend. (32451)
  • Storybook:
    • Fix misc warnings. (32401)
  • Data:
    • useSelect: Silently error (for block zombie children). (32088)

Performance

  • Block Editor: Remove is-typing root class. (32567)
  • Header Toolbar: UseCallback to avoid unnecessary rerenders. (32406)

Experiments

  • Component System:
    • Promote Scrollable component to a full export. (32446)
    • Promote Surface component to a full export. (32439)
  • Global Styles:
    • Allow presets to provide an empty set of values. (32679)
    • Allow theme authors hook into the preset classes generated by global styles. (32627)
    • Update WP_Theme_JSON API so presets are always keyed by origin. (32622)
    • Make syntax errors in theme.json visible to users. (32404)
    • Enqueue global styles in editor only once. (32377)
    • Enqueue core and theme colors by using separate structures per origin. (32358)
    • Do not migrate the old typography support if core already did it. (32487)
    • Generate classes and custom properties for global styles in the same way the post editor does. (32766)
  • Full Site Editing:
    • Template resolution for new posts and pages. (32442)
    • Monopolize navigation in Site Editor. (31810)
    • Prevent duplicate queries. (32700)
    • Split theme.css styles loading. (31239)
  • Navigation Editor:
    • Alternative fix: Set persisted menu id when no menus or missing menu. (32313)

Documentation

  • Handbook:
    • Update references to register_block_type_from_metadata. (32582)
    • Fix duotone support documentation. (32440)
    • Detail the Gutenberg release post process. (32429)
    • Update Legacy Widget documentation with new info on show_instance_in_rest feature. (32726)

Code Quality

  • Components:
    • Remove duplicated compose dependencies. (32709)
    • Sort entries in packages/components/tsconfig.json. (32675)
    • Update the popover component to rely on useDialog. (27675)
    • Card: Add types. (32561)
    • Card: Refactor subcomponents folder structure. (32557)
  • Compose:
    • Add types to useDialog and useFocusOnMount. (32676)
    • Add types to withSafeTimeout. (32674)
    • Type withState as any. (32326)
  • Block Library:
    • Page List: Avoid generic function names for page list block internal functions. (32736)
    • Latest Comments: Correct the format used for duplicate hook documentation. (32563)
    • Login/out: Update documentation for render_block_core_loginout function. (32158)
  • Block Editor: Remove unused select block function. (32532)
  • Core Data: Fix typos. (32480)
  • Editor: Fix different typos in inline comments, deprecation warnings and variable names. (32474)
  • Linting:
    • Edit Post: Fix no-string-literals warning. (32518)
    • Add ESLint import resolver. (31792)
  • Plugin:
    • Copy wp_should_load_separate_core_block_assets function from core. (32611)
    • Fix PHPCS Warnings. (32513)

Tools

  • Workflow:
    • Fix the add milestone github action. (32691)
    • Use a different cache key for the PR automation workflow. (32588)
    • Improvements to NPM package caching across workflows. (32458)
    • Limit when release artifacts are built on forks: Pt. 2. (32494)
  • Build:
    • Load .min.js files even in dev mode, output unminified assets only in prod. (32621)
    • Upgrade husky package to the latest version. (32077)
    • Generate minified .min.js and unminified .js files for GB js entry points when building. (31732)
    • Include Legacy Widget block files in the plugin build. (32803)
  • End to End Tests:
    • Update mentions tests to use toMatchInlineSnapshot. (32727)
    • Add more user auto-completer (mentions) coverage. (32697)
    • Ignore JQMIGRATE (jQuery migrate) deprecation warnings. (32656)
  • Linting:
    • Update linting and formatting for test plugin files. (28033)
    • Update Eslint JSDoc package, introducing JSDoc line alignment check. (25300)
  • wp-env: Bump TT1 Blocks to v0.4.7. (32661)

Performance Benchmark

The following benchmark compares performance for a particularly sizeable post (~36,000 words, ~1,000 blocks) over the last releases. Such a large post isn’t representative of the average editing experience but is adequate for spotting variations in performance.

VersionLoading TimeKeyPress Event (typing)
Gutenberg 10.94.50s28.93ms
Gutenberg 10.84.91s30.30ms
WordPress 5.75.71s32.09ms

Kudos to all the contributors that helped with the release! 👏

Thanks, @priethor, @get_dave, and @mikeschroder for helping with the release post.  Thanks to @youknowriad and @bernhard-reiter for coordinating the release.

#block-editor, #core-editor, #gutenberg, #gutenberg-new

Thank you @mamaduka for handling this release and for the excellent release notes and “What’s New” post.

CSS Chat Agenda: June 24, 2021

This is the agenda for the upcoming CSS meeting scheduled for Thursday June 24 at 21:00 PM UTC.

The meeting will be held in the #core-css channel in the Making WordPress Slack.

  • Open Floor + CSS Link Share

If there’s any topic you’d like to discuss, please leave a comment below!

#agenda

Editor chat summary: 23rd June 2021

This post summarises the weekly editor chat meeting (agenda here) held on Wednesday, June 23, 2021 at 02:00 PM UTC in Slack. Moderated by @get_dave.

Gutenberg 10.9 Plugin release

WordPress 5.8 Beta 3

  • 22nd June 2021 saw the release of WordPress 5.8 Beta 3.
  • It was noted that there is still time for bug fixes and documentation to be written.
  • @desrosj explained that there is a 4th (unscheduled) Beta planned for later this week (likely Thursday or Friday) – if there are additional things you’d like to see get tested during the beta cycle (and not after RC), there’s still time to get those in.
  • The project board for Gutenberg and WordPress 5.8 still has outstanding items needing contributors.
  • Due dates for dev notes – the field guide is published on the same day as RC 1, which is this upcoming Tuesday. Ideally, all dev notes should be in by then. If there are any notes that will not be ready, they can be added to the guide after publish, but having them for that date is preferred.

Key Project updates

Updates were requested for the key projects:

Native Mobile Team

@mattchowning provided the update:

Shipped

  • React Native 0.64.x upgrade, including upgrade to React v17!

Coming Soon:

  • Gallery block refactor
  • Tooltips to help with Editor Onboarding

In Progress:

  • Further Editor Onboarding improvements: a help section and a “new” badge for new blocks
  • Starting work on improving the integration tests for mobile so mobile breakages are caught earlier
  • Block inserter search
  • Embed block
  • Global Style Support for colors

Global Styles

@nosolosw provided the update async:

Current focus is polishing the theme.json experience by finding and fixing bugs that are backported to the Betas weekly.The two major things left are:

  • Show preset strings provided via theme.json in translate.wordpress.org so they can be translated. This depends on a new wp-cli release (see) and then updating the meta infrastructure. Trac ticket.
  • Publish dev note for theme.json (I’m working on this).

Block based Widget Editor and Customizer.

@andraganescu provided the update.

Navigation Block

@mkaz provided an update:

  • Color overlay issues being worked and continued improvements.
  • It looks like the markup has been confirmed so will need review on the open PR to move it forward

Navigation Editor screen

@get_dave provided an update:

Full Site Editing

Task Coordination

@ntsekouras:

@annezazu:

  • I was out last week – still playing catch up.
  • Hyper focused on the FSE Outreach program.
  • Working on the theme.json call for testing with a few folks
  • Nearly done with the seventh call for testing summary post.
  • Shared a reflection previously on future programs (thoughts welcome).
  • Starting July 1, I’ll be focusing in as much time as I can on user docs for 5.8.

@mkaz:

  • Looking at Dev Notes for WP 5.8, the tracking issue is here.
  • The three major dev notes that I see left are:
    • Widgets Editor
    • Global Styles
    • Block API & registration
  • @gziolo already has a draft of the Block API note that I hope to review and publish this week. 
  • @andragan and @nosolosw are working on the other two: Widgets & Global Styles.

@get_dave:

@aristath:

  • WP 5.8 – working on improving styles & scripts loading and there are no blockers
  • We should stop using FSE as a term, and eliminate it from code whenever possible (see note above).

@zieladam:

  • I am getting back into the rhythm of contributing after my 6 months break (during which I explored data science in Tumblr).
  • Mostly going through the Widgets editor board and reviewing/submitting new PRs and refreshing my memory of how everything works.

Open Floor

Saving Flow Consistency (agenda comment)

  • @paaljoachim asking about saving flow consistency across various screens.
  • He’s made a detailed overview Issue and he feels “…it would be helpful to get this fixed for WP 5.8, so users who want to discard a save does not meet these errors.“
  • Is anyone able to take a look into this? Please let us know in the comments.

“Final call” for input on the transform vs convert debate for Block Transform API

Feedback about Block based Widgets screen

Note: this has subsequently been converted into an Issue and added to the Widgets project board.

Request for pull request approval: filters to get block templates functions

Problems testing Theme JSON for Classic Themes

  • @colorful-tones is eager to test leveraging just the theme.json for classic theme (or more like hybrid) approach.
  • Saw PR #32858, but not entirely certain how to test and verify. Should I be running latest Gutenberg plugin and latest WP Beta 3, or just latest Gutenberg? 
  • @annezazu provided advice:

@colorful-tones I might recommend asking directly on the PR to be extra safe. From what I can see to test this, you need to use WordPress 5.7 and the specific branch that this PR is on.

Anne McCarthy

WordCamp Japan Contributor Day successes

No blocks in inserter on Widget screen with empty Widget area

Wrap up

It was great to hear/see so many voices in the Open Floor section.

Thanks to everyone who attended.

#core-editor, #core-editor-summary, #meeting-notes, #summary

Block API Enhancements in WordPress 5.8

Starting in WordPress 5.8 release, we encourage using the block.json metadata file as the canonical way to register block types. The Block Metadata specification has been implemented and iterated over the last few major WordPress releases, and we have reached the point where all planned features are in place.

Example File

Here is an example block.json file that would define the metadata for a plugin create a notice block.

notice/block.json

{
	"apiVersion": 2,
	"name": "my-plugin/notice",
	"title": "Notice",
	"category": "text",
	"parent": [ "core/group" ],
	"icon": "star",
	"description": "Shows warning, error or success notices…",
	"keywords": [ "alert", "message" ],
	"textdomain": "my-plugin",
	"attributes": {
		"message": {
			"type": "string",
			"source": "html",
			"selector": ".message"
		}
	},
	"providesContext": {
		"my-plugin/message": "message"
	},
	"usesContext": [ "groupId" ],
	"supports": {
		"align": true
	},
	"styles": [
		{ "name": "default", "label": "Default", "isDefault": true },
		{ "name": "other", "label": "Other" }
	],
	"example": {
		"attributes": {
			"message": "This is a notice!"
		}
	},
	"editorScript": "file:./build/index.js",
	"script": "file:./build/script.js",
	"editorStyle": "file:./build/index.css",
	"style": "file:./build/style.css"
}

Benefits using the metadata file

The block definition allows code sharing between JavaScript, PHP, and other languages when processing block types stored as JSON, and registering blocks with the block.json metadata file provides multiple benefits on top of it.

From a performance perspective, when themes support lazy loading assets, blocks registered with block.json will have their asset enqueuing optimized out of the box. The frontend CSS and JavaScript assets listed in the style or script properties will only be enqueued when the block is present on the page, resulting in reduced page sizes.

Furthermore, because the Block Type REST API Endpoint can only list blocks registered on the server, registering blocks server-side is recommended; using the block.json file simplifies this registration.

Last, but not least, the WordPress Plugins Directory can detect block.json files, highlight blocks included in plugins, and extract their metadata. If you wish to submit your block(s) to the Block Directory, all blocks contained in your plugin must have a block.json file for the Block Directory to recognize them.

Block registration

PHP

The register_block_type function that aims to simplify the block type registration on the server, can read now metadata stored in the block.json file.

The function takes two params relevant in this context ($block_type accepts more types and variants):

  • $block_type (string) – path to the folder where the block.json file is located or full path to the metadata file if named differently.
  • $args (array) – an optional array of block type arguments. Default value: []. Any arguments may be defined.

It returns the registered block type (WP_Block_Type) on success or false on failure.

Example:

notice/notice.php

<?php

register_block_type(
	__DIR__,
	array(
		'render_callback' => 'render_block_core_notice',
	)
);

Note: We decided to consolidate the pre-existing functionality available with register_block_type_from_metadata method into register_block_type to avoid some confusion that it created. It’s still possible to use both functions, but we plan to use only the shorter version in the official documents and tools from now on.

Related Trac ticket#53233.

JavaScript

If you don’t want to register the block on the server with PHP – not recommended in the context of WordPress for the reasons above – you can use now registerBlockType method from @wordpress/blocks package to register a block type using the metadata loaded from block.json file.

The function takes two params:

  • $blockNameOrMetadata (string|Object) – block type name (supported previously) or the metadata object loaded from the block.json file with a bundler (e.g., webpack) or a custom Babel plugin.
  • $settings (Object) – client-side block settings.

It returns the registered block type (WPBlock) on success or undefined on failure.

Example:

notice/index.js

import { registerBlockType } from '@wordpress/blocks';
import Edit from './edit';
import metadata from './block.json';

registerBlockType( metadata, {
	edit: Edit,
	// ...other client-side settings
} );

Related PR: WordPress/gutenberg#32030.

Internationalization support in block.json

WordPress string discovery system can now automatically translate fields marked as translatable in Block Metadata document. First, in the block.json file that provides block metadata, you need to set the textdomain property and fields that should be translated.

Example:

fantastic-block/block.json

{
	"name": "my-plugin/fantastic-block",
	"title": "My block",
	"description": "My block is fantastic",
	"keywords": [ "fantastic" ],
	"textdomain": "fantastic-block"
}

PHP

In PHP, localized properties will be automatically wrapped in _x function calls on the backend of WordPress when executing register_block_type function. These translations get added as an inline script to the plugin’s script handle or to the wp-block-library script handle in WordPress core.

The way register_block_type processes translatable values is roughly equivalent to the following code snippet:

<?php
$metadata = array(
	'title'       => _x( 'My block', 'block title', 'fantastic-block' ),
	'description' => _x( 'My block is fantastic!', 'block description', 'fantastic-block' ),
	'keywords'    => array( _x( 'fantastic', 'block keyword', 'fantastic-block' ) ),
);

Implementation follows the existing get_plugin_data function which parses the plugin contents to retrieve the plugin’s metadata, and it applies translations dynamically.

Related Trac ticket: #52301.

JavaScript

You can also now use registerBlockType method from @wordpress/blocks package to register a block type that uses translatable metadata stored in block.json file. All localized properties get automatically wrapped in _x function calls (from @wordpress/i18n package) similar to how it works in PHP with register_block_type. The only requirement is to set the textdomain property in the block.json file.

Example:

fantastic-block/index.js

import { registerBlockType } from '@wordpress/blocks';
import Edit from './edit';
import metadata from './block.json';

registerBlockType( metadata, {
	edit: Edit,
	// ...other client-side settings
} );

Related PR: WordPress/gutenberg#30293.

Extracting translations

The ongoing effort to improve the internationalization of client-side JavaScript code made necessary by moving to the block-based editor has led to several improvements to the i18n make-pot command from WP-CLI as of v2.5.0 release. It now also parses the block.json file as it is defined in the Block Metadata document.

Related PR: wp-cli/i18n-command#210.

New filters

There are two new WordPress hooks that can be used when block types get registered with register_block_type function using the metadata loaded from the block.json file.

block_type_metadata

Filters the raw metadata loaded from the block.json file when registering a block type. It allows applying modifications before the metadata gets processed.

The filter takes one param:

  • $metadata (array) – metadata loaded from block.json for registering a block type.

Example:

<?php

function filter_metadata_registration( $metadata ) {
	$metadata['apiVersion'] = 1;
	return $metadata;
};
add_filter( 'block_type_metadata', 'filter_metadata_registration', 10, 2 );

register_block_type_from_metadata( __DIR__ );

block_type_metadata_settings

Filters the settings determined from the processed block type metadata. It makes it possible to apply custom modifications using the block metadata that isn’t handled by default.

The filter takes two params:

  • $settings (array) – Array of determined settings for registering a block type.
  • $metadata (array) – Metadata loaded from the block.json file.

Example:

function filter_metadata_registration( $settings, $metadata ) {
	$settings['api_version'] = $metadata['apiVersion'] + 1;
	return $settings;
};
add_filter( 'block_type_metadata_settings', 'filter_metadata_registration', 10, 2 );
		
register_block_type_from_metadata( __DIR__ );

Props to @priethor and @audrasjb for help with compiling this dev note.

#5-8, #dev-notes, #gutenberg

so in short,

1. do `register_block_type` in PHP giving it the dir with the `block.json`
2. `block.json` enqueues the `editorScript`
3. the `editorScript` should not call `registerBlockType`

This post tells me nothing about the `editorScript`. The way it works in http://wayback.fauppsala.se:80/wayback/20210628044831/https://github.com/WordPress/gutenberg/blob/trunk/packages/block-library/src/index.js blocks are registered with `registerBlockType` which is, according to this post, discouraged in favor of PHP’s `register_block_type`.

What are the requirements for the `editorScript`? I suppose it needs to export a global object. What is the name of the global variable? What are the requirements for the exported object? I assume the same as what `registerBlockType` expects?

> the `editorScript` should not call `registerBlockType`

This is incorrect. You still need to call `registerBlockType` function on the client using the same block name and provide at least `edit` implementation for the block to register it on the client. In general, everything that can’t be serialized in JSON format like JavaScript functions needs to be handled on the client.

We are going to update the post and clarify it better. The short answer is that the `editorScript` script needs to contain the `registerBlockType` call.

A Week in Core – June 21, 2021

Welcome back to a new issue of Week in Core. Let’s take a look at what changed on Trac between June 14 and June 21, 2021.

  • 58 commits
  • 61 contributors
  • 83 tickets created
  • 7 tickets reopened
  • 52 tickets closed

Please note that the WordPress Core team released WordPress 5.8 beta 2 last week. Everyone is welcome to help testing the next major release of WordPress 🌟

Ticket numbers are based on the Trac timeline for the period above. The following is a summary of commits, organized by component and/or focus.

Code changes

Administration

  • Consistently escape admin_url() links – #53426
  • Consistently escape network_admin_url() links – #53459

Build/Test Tools

  • Ignore sourceMaps for non WordPress Core files – #52689
  • Replace the deprecated @babel/polyfill#52941
  • Use Git when fetching the WordPress Importer for use in tests – #52909
  • Correct svn:eol-style property for test data with CR line endings – #52625
  • Make some optional parameters required in unit tests for previous/next attachment links – #45708, #52625
  • Use more appropriate assertions in clean_dirsize_cache() tests – #52625
  • Use more appropriate assertions in a few tests – #52625

Bundled Themes

  • Improve Gutenberg check before activating an FSE theme – #53410
  • Make sure get_file_data() recognizes headers prefixed by <?php tag#33387
  • Prevent a Full Site Editing theme from being activated when Gutenberg is not active – #53410
  • Remove unexpected border around the Theme Details button – #53473
  • Twenty Thirteen: Improve the display of the Query Loop block#53438
  • Twenty Twenty-One: Add margins around content in Post Template block – #53389, #53398

Coding Standards

  • Apply some alignment fixes – #50105
  • Bring some consistency to HTML formatting in wp-admin/comment.php#52627
  • Fix WPCS issue in [51174]#53407
  • Remove a one-time $message variable in WordPress version requirement notices for bundled themes – #52627
  • Remove a one-time $message variable in some _doing_it_wrong() calls – #52627
  • Use consistent formatting for _wp_posts_page_notice() and _wp_block_editor_posts_page_notice()#45537, #52627

Documentation

  • Add a reference to WP_Site_Query::__construct() for information on accepted arguments in get_sites()#42156
  • Add missing documentation for wp_migrate_old_typography_shape()#52991, #52628
  • Correct DocBlock formatting for Core_Upgrader::upgrade()#52628
  • Correct @since version in the wp-includes/version.php file header#52628
  • Document the VALID_ORIGINS constant in WP_Theme_JSON#52628
  • Document the usage of $_wp_current_template_content global in a few block template functions – #52628
  • Document the usage of $wp_embed global in WP_oEmbed_Controller::get_proxy_item()#52628
  • Update syntax for multi-line comment in wp_generate_attachment_metadata() per the documentation standards – #52603
  • Update syntax for some multi-line comments per the documentation standards – #52628

Editor

  • Remove code from a translatable string in wp_migrate_old_typography_shape()#52991
  • Allow custom-units to be an array – #53472
  • Check if supports metadata key is defined before migrating typography keys – #53416
  • Include Cover block in the list of block types registered using metadata files – #53440
  • Replace a Gutenberg specific function with the Core equivalent – #53369
  • Package updates for Beta 3 – #53397
  • Prevent duplicate queries – #53280, #53176
  • Second batch of fixes for 5.8 beta 2 – #53397
  • Update the WordPress packages with the fixes for 5.8 beta 2 – #53397
  • Ports theme.json changes for beta 3 – #53397

External Libraries

  • Upgrade PHPMailer to version 6.5.0 – #53430

Internationalization

  • Remove redundant default text domain parameter in some __() calls – #52627
  • Use consistent pattern for placeholder references in translator comments for some bundled theme strings – #52628

Media

  • Adapt response shape depending on type of query – #53421, #53419
  • Ensure $post_ids is evaluated properly when processing bulk actions – #53411
  • Improve upload page media item layout on smaller screens – #51754
  • Make sure wp_generate_attachment_metadata() always returns an array – #52603
  • Restore AJAX response data shape in media library – #50105
  • Update total attachment count when media added or removed – #53171

Quick/Bulk Edit

  • Ensure that $post_ids variable is initialized ahead of usage – #39589, #53411

REST API

  • Decode HTML entities in widget names and descriptions in widget types controller – #53407
  • Decode single and double quote entities in widget names and descriptions – #53407

Upgrade/Install

  • Deactivate the Gutenberg plugin if its version is 10.7 or lower – #53432

Users

  • Escape get_author_posts_url() link in wp_list_authors()#50698

Widgets

  • Add editor styles to the widgets block editor – #53344, #53388
  • Stop loading wp-editor and the Block Directory assets on the widgets screen – #53437, #53397

Props

Thanks to the 61 people who contributed to WordPress Core on Trac last week: @desrosj (6), @noisysocks (5), @nosolosw (4), @youknowriad (4), @ryelle (4), @adamsilverstein (3), @audrasjb (3), @walbo (3), @SergeyBiryukov (3), @peterwilsoncc (3), @chintan1896 (3), @jorbin (3), @hellofromTonya (3), @david.binda (2), @joedolson (2), @ramonopoly (2), @gziolo (2), @jorgefilipecosta (2), @spacedmonkey (2), @mukesh27 (2), @Presskopp (2), @alexstine (1), @jnylen0 (1), @czapla (1), @francina (1), @markparnell (1), @kraftner (1), @justinahinon (1), @afragen (1), @johnbillion (1), @ayeshrajans (1), @TimothyBlynJacobs (1), @Synchro (1), @Chouby (1), @aristath (1), @ntsekouras (1), @mcsf (1), @chaion07 (1), @Clorith (1), @ocean90 (1), @pbiron (1), @chanthaboune (1), @Mamaduka (1), @mkaz (1), @joen (1), @isabel_brison (1), @andraganescu (1), @caseymilne (1), @sabernhardt (1), @marybaum (1), @AlePerez92 (1), @azaozz (1), @scruffian (1), @birgire (1), @felipeelia (1), @dd32 (1), @m_uysl (1), @thomas-vitale (1), @boblinthorst (1), @oglekler (1), and @JeffPaul (1).

Congrats and welcome to our 3 new contributors of the week! @czapla, @caseymilne, and @AlePerez92 ♥️

Core committers: @sergeybiryukov (33), @desrosj (13), @joedolson (3), @jorgefilipecosta (2), @youknowriad (2), @ryelle (1), @peterwilsoncc (1), @antpb (1), @davidbaumwald (1), and @jorbin (1).

#5-8, #week-in-core

Extending the Site Health interface in WordPress 5.8

With WordPress 5.8, the feature request to allow developers to extend what Site Health tabs are available (#47225) has been implemented.

This will allow developers to add their own interfaces to the Site Health area of core, with accompanying tab navigation in the Site Health header, or even extend another interface.

Site Health screen showing 4 navigation items

Registering your tab navigation

If you are adding a brand new interface, you will want to introduce a navigation element, so that users may access your interface. This is done using the new site_health_navigation_tabs filter, which is an associated array of tab keys, and their label.

1
2
3
4
5
6
7
8
<?php
function wp_example_site_health_navigation_tabs( $tabs ) {
    // translators: Tab heading for Site Health navigation.
    $tabs['example-site-health-tab'] = esc_html_x( 'My New Tab', 'Site Health', 'text-domain' );
 
    return $tabs;
}
add_filter( 'site_health_navigation_tabs', 'wp_example_site_health_navigation_tabs' );

The above example will add the identifier example-site-health-tab with the label My New Tab to the header navigation i Site Health pages.

It is also possible to re-order what tabs are displayed first using this filter, or even remove tabs. By default core has two tabs, the Status and Info screens. The Status screen is the default, and therefore has no slug.

To not overburden the navigation area, if there are more than 4 items added, only the first three will be displayed directly, with the remaining items being wrapped inside a sub-navigation. This is based on usage testing in the Health Check plugin, where 4 items have shown to be enough to cover most use cases, but not so many as to become confusing.

Displaying, or extending, an interface

When a user visits a Site Health tab, other than the default screen, the site_health_tab_content action triggers. This action includes a single argument being the slug, as defined by the tab navigation in the previous filter, to help you identify which page is being requested.

The action fires after the header itself has been loaded, but does not include any wrappers. This gives you as a developer the full width of the screen (not counting the admin menu) to work with.

1
2
3
4
5
6
7
8
9
10
11
<?php
function wp_example_site_health_tab_content( $tab ) {
    // Do nothing if this is not our tab.
    if ( 'example-site-health-tab' !== $tab ) {
        return;
    }
 
    // Include the interface, kept in a separate file just to differentiate code from views.
    include trailingslashit( plugin_dir_path( __FILE__ ) ) . 'views/site-health-tab.php';
}
add_action( 'site_health_tab_content', 'wp_example_site_health_tab' );

The above example loads in a file with your tab content from your plugin, but only if the tab matches the tab key (or slug if you will) which was defined in the previous example.

It is possible to provide output on any tab this way, or on another tab not your own, for example if they interact with each other.

One such example might be to extend the default Info tab, which has the slug debug, and add a button to copy some information specific to only your plugin or theme.

Props @afragen for review and edits.

#5-8, #dev-notes, #site-health

Dev Chat Agenda for June 23, 2021

Here is the agenda for this week’s developer meetings to occur at the following times: Wednesday, June 23, 2021 at 05:00 AM UTC and Wednesday, June 23, 2021 at 08:00 PM UTC.

Blog Post Highlights

5.8 Schedule Review

  • Beta 3 released yesterday and a soft string freeze, our focus now shifts to RC phase with RC1 release in 6 days on Tuesday, June 29th
  • Focus now on publishing Dev Notes and eventual Field Guide, committing the About page, drafting the release post, and a hard string freeze
  • Next Beta Scrub before RC 1 is Monday, June 28, 2021 at 08:00 PM UTC
  • RC 1 in 6 days on Tuesday, June 29th
  • 5.8 release in 27 days on Tuesday, July 20th

Components check-in and status updates

  • 5.8 plans and help needed
  • Check-in with each component for status updates.
  • Poll for components that need assistance.

Open Floor

Do you have something to propose for the agenda, or a specific item relevant to the usual agenda items above?

Please leave a comment, and say whether or not you’ll be in the chat, so the group can either give you the floor or bring up your topic for you accordingly.

This meeting happens in the #core channel. To join the meeting, you’ll need an account on the Making WordPress Slack.

#5-8, #agenda, #dev-chat

Hi there, I have something for the open floor. It’s a minor improvement to the Meta Query. It adds easier and more performant compare operators for “Startswith” and “Endswith” value queries.
Currently this requires one to use Regex. I encountered regularly that people use Regex on a copy and paste base without really understanding them. Also escaping requirements for regex operators is very error prone. In addition to that, “REGEXP” is one of the slower SQL compare operators.
Taking a look from the “how to do this if you control the SQL query”, the answer would be a simple “LIKE” compare, adding the wildcard before or after the query. Especially as LIKE is also faster than REGEXP (see ticket for benchmark link).
The usage of the Meta Query compare operator LIKE in this case is sadly not possible with WP_Meta_Query because for historic reasons the only available “LIKE” operator is a “CONTAINS” query in reality, adding wildcards before and after with no possibility to change this behavior.

The following ticket (Patch and Tests all there) solves this by adding two more distinct LIKE compare modes. Allowing arbitrary LIKE queries would be the “gold” solution but woild also require alot of thoughts and work. Thus I focused this on a useful and easily shippable improvement.
I would love some core dev feedback on this.

http://wayback.fauppsala.se:80/wayback/20210628044831/https://core.trac.wordpress.org/ticket/53450

I will most probably not be able to join in the live chat sessions. But all information should be here and in the ticket.
If questions arise, I will answer them in the ticket or next week’s chat session.

Thanks and best regards,

Jan

Sure thing @janthiel, I’ll ensure to call that out during open floor… thanks!

Editor chat summary: Wednesday, 16 June 2021

This post summarizes the weekly editor chat meeting on Wednesday, 16 June 2021, 14:00 UTC held in Slack.

Gutenberg 10.8 release.

The first topic was the Gutenberg 10.8 release. The release was already shipped a week before the chat http://wayback.fauppsala.se:80/wayback/20210628044831/https://make.wordpress.org/core/2021/06/10/whats-new-in-gutenberg-10-8-9-june/.

@jorgefilipecosta referred the main features of the 10.8 release (more block design tools and template editor enhancements) and added the Gutenberg 10.9 RC was going to be released soon.

@mamaduka will handle the 10.9 release, with @get_dave in the “shadow” and @youknowriad coordinating. Thank you all!

Monthly Plan and key project updates.

Mobile

  • Shipped:
    • Reusable blocks rendering and converting to normal blocks.
  • Soon:
    • RN upgrade to 0.64.x – Merge is very close
  • In progress
    • Gallery Block Refactor – Almost done
    • Editor Onboarding
    • Global Style Support – Colors
    • Adding search to the block inserter
    • Embed block
    • iOS share extension

Global Styles

The shape of the typography block.json supports was updated to be consistent with the colors and theme.json shape. The data structures used internally were updated to keep track of each preset origin this open path to show multiple palettes e.g: theme and use for example.

Navigation block

The navigation block is still on deck and is getting home link improvements, invalid item flagging, and hopefully soon separate overlay colors. The big nav markup also remains on the to-do list.

Navigation editor

  • Exploring methods to provide a better way to disable/enable nav block features for the nav editor. Watch for incoming Issue on this soon!
  • Exploring creation of a reordering endpoint extension for the Menus API endpoint.
  • Looking into converting the persistence to utilise the REST bulk API.

Feel free to join to chat for this feature over at #feature-navigation-block-editor.

Block based Widget Editor

The bug fixing work is in progress, every week a big set of issues is solved.

Task Coordination

@aristath

This week’s highlights:

  • Needs discussion/opinions/Review: Working on allowing more than 1 block-styles per-block (#32510). Will help with blocks that need to load styles from other blocks (example: comment-form loads button styles) and will also allow plugin & theme-authors to style individual blocks more efficiently.
  • Needs review: Allow decimals in spacing controls when using units like emrem etc – #32692
  • Merged: Did for theme.css the same we did for style.css a few months ago to increase performance and load styles when a block gets rendered on the front (#31239)
  • Merged: Fixed a performance issue with the latest-posts block when there are many users in the database (#32620)
  • Backported commits from Gutenberg to wp-core
  • Lots of PR reviews

Next week: Continue working on performance improvements, styles & scripts loading, PR reviews, and any bugs that come my way

@getdave

@paaljoachim

Is focusing on fixing Reusable block features.
At the moment focusing on adding a lock to the toolbar. A PR has been created here that could use some feedback: http://wayback.fauppsala.se:80/wayback/20210628044831/https://github.com/WordPress/gutenberg/pull/32710.

@mamaduka

  • Fixed “cover block exists” check for Image Block.
  • Worked on logic to hide settings from the “Options” menu in Widget editor on small screens.
  • Helping with new Widget Screen issues.
  • Helping with PR reviews.

@jorgefilipecosta

During the last week the main focus was the theme.json/global styles changes. For the next week: will help ship the theme.json dev note; Review PR’s that are pending review; Fix some bugs where he was pinged, and plans on restarting the work to advance the global styles UI. Will also help to ship the new enhancements to our locking API.

@andraganescu

Is focused on advancing the text based tasks around the widgets project (docs, dev note etc).

Open floor

Transforms vs convert API

@get_dave brought the following topic:

I’ve followed up on the `transform` vs `convert` API discussion with x2 options/suggestions for how we could come to a decision.

It’s not a huge problem, but it would be nice to see us unify around a single API for this action. Indeed `convert` has been “experimental” for over 2 years.

I believe this needs guidance from the Core team.

Adding that there are two options:

  1. Deprecate transform in favour of convert
  2. Augment the argument signature of transform and ditch convert.

On the issue @talldanwp referred that he is in favor of deprecating transform in favor of convert. During the chat and then in a comment in the issue @youknowriad said @talldanwp thoughts sound reasonable.

Dot in the Publish/Update button

@bobbingwide asked:

What happened to the dot in the Publish/Update button?
It’s still there when I edit a reusable block. http://wayback.fauppsala.se:80/wayback/20210628044831/https://sneak-peek.me/2021/06/16/what-does-the-dot-next-to-update-mean/

@jorgefilipecosta said the best path forward would be to have an issue where this issue could be discussed. @paaljoachim created the issue.

Click through vs lock for some blocks

@paaljoachim said:

I think we need a way to figure out if a block should have a click through or/and also a lock. Reusable block could really use a lock similar to the edit button in WP 5.6.

@joen said:

I worry that a lock icon and toolbar action will not be an obvious affordance for editing the contents, or help indicate why this block is any different from the surrounding blocks which you can click and edit. I think some of Jays designs from the previous ticket have potential.

This is a UX decision and the discussion will continue on the issues and related PR’s.

#block-editor, #chats, #core-editor, #core-editor-summary, #gutenberg, #meeting-notes-2