New API to access global settings & styles

Following the introduction of a theme.json API in WordPress 5.8 and its corresponding JavaScript API, WordPress 5.9 comes with a PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher public 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. to read data from theme.json.

Access to settings & styles

The following new functions give access to the settings and styles keys found in a theme.json:

wp_get_global_settings( $path = array() , $context = array() );
wp_get_global_styles( $path = array(), $context = array() );

where:

  • $path is a list with the path to the speciffic setting, e.g.: array( 'color', 'link' ) returns the setting stored at settings.color.link. If no path is provided, all settings are returned.
  • $context is a named array through which consumers can have a finer-grained control of the data returned:
    • using the block_name key, consumers can access the settings of a particular 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.. For example, array( 'block_name' => 'core/paragraph' ) returns only the settings of the paragraph block.
    • using the origin key, consumers can decide to ignore custom data coming from the user by setting it to base. Otherwise, the data returned will be the result of merging defaults, theme, and custom data.

Some examples:

// Returns all settings
// after merging defaults, theme, and user data.
wp_get_global_settings(); 


// Returns the blockGap setting
// after merging defaults, theme, and user data.
wp_get_global_settings( array( 'spacing', 'blockGap' ) );

// Returns the borderRadius style for the group block
// after merging default, theme, and user data.
wp_get_global_styles(
  array( 'border', 'radius' ),
  array( 'block_name' => 'core/group' )
); 

// Returns the background color for the block paragraph
// after merging defaults and theme data (ignoring user data).
wp_get_global_styles(
  array( 'color', 'background' ),
  array(
    'block_name' => 'core/paragraph',
    'origin'     => 'base',
  )
); 

Access to the resulting stylesheet

Additionally, there’s a function to generate the stylesheet resulting of merging defaults, theme, and custom settings and styles:

wp_get_global_stylesheet( $types = array() );

where $types is a list of the styles to generate. Valid values are:

  • presets, the classes coming from the presets, e.g.: .has-black-color { ... }.
  • styles, the classes coming from the styles section of 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., e.g.: .wp-block-group {...}.
  • variables, the CSSCSS Cascading Style Sheets. Custom Properties coming from the presets and the custom section of the theme.json, e.g.: --wp--preset--duotone--dark-grayscale.

This function also considers whether the theme has theme.json support or not, abstracting that implementation detail from the consumers. By default, all styles are returned if the theme supports theme.json; if it doesn’t, only styles for variables and presets are returned.

Note that this function only takes care of generating the stylesheet string, it doesn’t actually enqueue any styles.


Props to @oandregal for creating 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 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., it was review and published by me (@mkaz).

#5-9, #dev-notes

WordPress 5.9 Performance Improvements

Thank you to @aristath @piyopiyofox @bph @mkaz @flixos90 @youknowriad who helped review this post. 

Whether you’re using the latest and greatest with full site editing features or not, there are performance enhancements that everyone can look forward to with WordPress 5.9 set to launch January 25th, 2022. At a high level, you can expect improvements to the Inserter, 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. Themes, List View, and more. 

Editor performance

This section touches on the actual experience of creating content within the editor itself. Does the Inserter open quickly, allowing you to snag what you need? Does using List View feel smooth and snappy? These are the kinds of experiences that have been focused on and improved for 5.9. 

Inserter 

The Inserter is a very commonly used tool in the editing experience that allows you to select any block or pattern you’d like to build with. As the number of blocks and patterns grow, the Inserter needs to be able to keep up to make it easy to add what you need. To aid in usability, lazy render has been applied to the Inserter in two instances: when searching block types and patterns, and when displaying categories. 

By lazy-rendering search results, the initial results are provided faster when you search. With the same lazy-rendering approach applied to categories, they now render one by one. Both improvements allow the browser to do higher priority things and ensure a better experience (like actually opening the Inserter quickly) before continuing to take care of other processes, like displaying categories. 

Reusable Blocks

For larger sites with lots of reusable blocks, saved reusable blocks are now significantly faster when a site has thousands of them. This helps fulfill the promise of WordPress growing with you. The coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. of this improvement was achieved by implementing a method that extracts the tokenizer regular expression used in package block-serialization-default-parser, and uses it to match the very first block boundary found in a reusable block’s markup.

List View

List View is an increasingly used tool to help folks navigate complex content with ease. A big part of ensuring it can be done with ease comes down to performance considerations, especially if you have a large amount of content in a page or template. When we say large, we mean it–we tested posts with 10,000 blocks. Thanks to a windowing technique that now renders a fixed number of items at a time instead of every block, the enhanced List View continues to scale as your content does. 

Front end performance

This section touches on site visitor experience and the resulting impact on SEO. Does your site render quickly? Is only what’s necessary loaded as needed? What can one do as 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 or theme author to ensure solid performance? While loads of things impact front end performance, there are quite a few enhancements coming to WordPress 5.9 that focus on these kinds of questions: 

Block Themes

If you’re using a Block Theme, you’ll be able to take advantage of enhanced site performance thanks to 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. enqueuing all styles from one place as a “global stylesheet”. This will reduce the amount of CSSCSS Cascading Style Sheets. shipped with a theme and result in fewer specificity wars.

Block Stylesheets & CSS Loading

In previous releases, all styles for all blocks were enqueued in a single file, leading to extra page load. With the 5.9 release, only what’s necessary is loaded when viewing content due to improvements that inline tiny stylesheets, and a tweak to only load a block’s CSS styles if the block exists on the page. Further, IE polyfills were removed from block front-facing scripts to reduce their size. By cutting down on the amount of CSS loaded, the 5.9 release increases performance and decreases loading time dramatically. 

Add additional stylesheets on a per-block basis to reduce CSS impact

Block and theme developers can now add additional stylesheets on a per-block basis instead of loading monolithic stylesheets– further reducing the CSS impact on a page. For Block developers, this allows for complex blocks to reuse styles they need from other blocks without the need to duplicate those same styles. For theme developers, you can now use a new wp_enqueue_block_style() function that allows you to register stylesheets on a per block basis to reduce any unnecessary styles loading. Here’s a dev note with more information.

Improvements to Lazy Loading images

Building on the excellent work to implement lazy loading images in WordPres 5.5, performance improvements are coming baked into WordPress 5.9 without needing any extra efforts from developers. At the core of this change is that WordPress will now skip the very first “content image or iframeiframe iFrame is an acronym for an inline frame. An iFrame is used inside a webpage to load another HTML document and render it. This HTML document may also contain JavaScript and/or CSS which is loaded at the time when iframe tag is parsed by the user’s browser.” on the page from being lazy-loaded. As you can see in the comprehensive dev note that details this change, “an analysis taking into account 50 popular themes showed that the enhancementenhancement Enhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature. brought LCP improvements across the board, up to 30% faster page load”

What do the numbers show? 

Numbers help paint a picture that words can’t always. Below is a snapshot of this release where you’ll see decreased loading times in a variety of editor areas, with only two gaining nominal loading time increases in the build.

FeatureDescriptionWP 5.6WP 5.7WP 5.8WP 5.9Diff
LoadingTime to first block (ms)3311.884773.943457.623184.38-7.90%
TypingTime to type a character (ms)54.2564.2453.6341.52-22.58%
Block selectionTime to select a block (ms)78.2166.5689.82101.89+13.44%
Inserter openingTime to open the global inserter (ms)98.91124.21134.8637.87-71.92%
SearchTime to type in the inserter search input (ms)38.8669.46124.1173.26-40.97%
HoverTime to move the mouse between two block items in the inserter (ms)37.7924.7923.5226.23+11.52%

If you’re interested in improving performance in WordPress, join the performance meetings, review the current performance related Trac and Gutenberg issues, help with the performance plugin, and test everything with performance considerations in mind.

Changelog:

  • Jan 6 2022: Updated to correct the diff values in the chart. All values were updated.

#5-9, #core-editor, #performance

Performance team meeting summary 11 January 2022

Meeting agenda here and the full chat log is available beginning here on Slack.

Focus group updates

Images

@adamsilverstein

GitHub project

  • @adamsilverstein offline
  • @mitogh: Researching existing functionality and working on planning. Can we include https://core.trac.wordpress.org/ticket/53232 in GH as part of image performance improvements?
  • @tweetythierry: Sure, this will help us do some testing before it lands in coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress..
  • @mitogh will create a new GH issue linking back to the TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. ticketticket Created for both bug reports and feature development on the bug tracker.
  • WebP module
    • Ready for testing
    • @tweetythierry: Should we remove the original image or not?
    • @boogah: Can we give the option? Keep the original and add a filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. to remove the original for users/hosts who wish to do so
    • @tillkruess, @madpixels, @craigfrancis: Keep the original
    • @blogaid: This will double disk space usage and we need to keep hosting costs in mind
    • @schlessera: webp is not supported everywhere, so we shouldn’t be removing the original
    • Several other users chimed in; see Slack
    • Continue the discussion on GitHubGitHub GitHub is a website that offers online implementation of git repositories that can can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged be the repository owner. https://github.com/ (see below)

Feedback requested

Object caching

@tillkruess

GitHub project

  • No updates

Feedback requested

  • N/A

Site Health

@audrasjb

GitHub project

Feedback requested

  • Create Site Health Audit Enqueued Assets module (inc. this PR) has been adapted to the new 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 structure and is open for discussion

Measurement

@wp-source @josephscott

GitHub project

  • @wp-source offline until end of January
  • @josephscott: Plan to get a live updating test site set up on platform.sh ot begin running tests on every commit to master soon

Feedback requested

JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/.

@aristath

GitHub project

Feedback requested

  • N/A

Infrastructure

Feedback requested

Open floor

  • @seedsca: Has anyone looked into using Xdebug with profiling for tests?
  • @craigfrancis: Looking for review on PR #2127 in Core since this is a feature change to wp-db

#core-media, #meeting, #performance, #performance-chat, #summary

Posts, Post types and Taxonomy changes in WordPress 5.9

In WordPress 5.9, new hooksHooks In WordPress theme and development, hooks are functions that can be applied to an action or a Filter in WordPress. Actions are functions performed when a certain event occurs in WordPress. Filters allow you to modify certain functions. Arguments used to hook both filters and actions look the same. and functions are added to help developers to work with Posts, Post types and Taxonomies.

is_post_type_viewable filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output.

WP 5.9 introduces the new is_post_type_viewable filter to allow developers to hook into is_post_type_viewable() to override the check performed by this function.

This filter exposes the $post_type object to allow to return either true or false depending on their needs. The expected filtered value is a boolean. As filtered values can change, including the data type, this commit includes a is_bool() check, thus ensuring backwards-compatibility and guard against potential type errors in PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher 8.1+. Non-boolean values (even falsey and truthy values) will result in the function returning false.

Usage:

/**
 * Override is_post_type_viewable() value for the "Books" custom post type. 
 */
function wporg_books_is_not_a_viewable_post_type( $is_viewable, $post_type ) {
	if ( __( 'Books', 'my-plugin' ) === $post_type->label ) {
		return false;
	}
	return $is_viewable;
}
add_filter( 'is_post_type_viewable', 'wporg_books_is_not_a_viewable_post_type', 10, 2 );

Related ticketticket Created for both bug reports and feature development on the bug tracker. on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress.: #49628.

is_post_status_viewable filter

Similarly to is_post_type_viewable, the is_post_status_viewable filter allow developers to hook into the related PHP function. This filter exposes the $post_status object to allow to return either true or false depending on their needs.

Usage:

/**
 * Override is_post_status_viewable() value for the "Unread" custom post status. 
 */
function wporg_unread_is_not_a_viewable_post_status( $is_viewable, $post_status ) {
	if ( __( 'Unread', 'my-plugin' ) === $post_status->label ) {
		return false;
	}
	return $is_viewable;
}
add_filter( 'is_post_status_viewable', 'wporg_unread_is_not_a_viewable_post_status', 10, 2 );

Related ticket on Trac: #54375.

post_thumbnail_url filter

WP 5.9 Introduces the new filter post_thumbnail_url which allows overriding the default url returned from wp_get_attachement_image_url() function. It passes the following parameters:

  • $thumbnail_url: The Post thumbnail URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org (or false if the post does not exist)
  • $post: The Post ID or WP_Post object. Default is global $post
  • $size: The Registered image size to retrieve the source for or a flat array of height and width dimensions. Default value: post-thumbnail

Usage:

/**
 * Override the post thumbnail URL for a specific template.
 */
function wporg_change_post_thumbnail_url_for_about_template( $thumbnail_url, $post, $size ) {
	if ( 'templates/about.php' !== get_page_template_slug( $post ) ) {
		return wp_get_attachment_image_url( get_template_directory . '/images/my-specific-image.png' );
	}
	return $thumbnail_url;
}
add_filter( 'post_thumbnail_url', 'wporg_change_post_thumbnail_url_for_about_template', 10, 3 );

Related ticket on Trac: #40547.

post_thumbnail_id filter

Similarly, WP 5.9 introduces the new post_thumbnail_id filter which allows overriding the default id returned from get_post_thumbnail_id(). It passes the following parameters:

  • $thumbnail_id: The Post thumbnail ID (or false if the post does not exist)
  • $post: The Post ID or WP_Post object. Default is global $post

Related ticket on Trac: #23983.

New labels available in register_taxonomy()

In WP 5.9, some static strings were replaced with additional label options to allow developers further flexibility for customizing the Edit {taxonomyTaxonomy A taxonomy is a way to group things together. In WordPress, some common taxonomies are category, link, tag, or post format. https://codex.wordpress.org/Taxonomies#Default_Taxonomies.} screen.

The following labels were added:

  • name_field_description: Description for the Name field on Edit Tags screen. Default: “The name is how it appears on your site.”
  • parent_field_description: Description for the Parent field on Edit Tags screen. Default: “Assign a parent term to create a hierarchy. The term Jazz, for example, would be the parent of Bebop and Big Band.”
  • slug_field_description: Description for the Slug field on Edit Tags screen. Default: “The « slug » is the URL-friendly version of the name. It is usually all lowercase and contains only letters, numbers, and hyphens.”
  • desc_field_description: Description for the Description field on Edit Tags screen. Default: “The description is not prominent by default; however, some themes may show it.”

Related ticket on Trac: #43060.

New function to get the URL for existing revisionsRevisions The WordPress revisions system stores a record of each saved draft or published update. The revision system allows you to see what changes were made in each revision by dragging a slider (or using the Next/Previous buttons). The display indicates what has changed in each revision. of a post: wp_get_post_revisions_url()

Since WP 5.9, the wp_get_post_revisions_url() function can be used to get a link to a given post’s revisions.

Parameters:

  • $post_id (optional): Post ID or WP_Post object. Default is global $post.

This function returns the URL for editing revisions on the given post (or null otherwise).

Related ticket on Trac: #39062.

New built-in post types in WP 5.9

Please note that WordPress 5.9 introduces four new built-in post types related to the new full site editing experience and are used when 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 is activated.

  • wp_template: The templates to include in your theme.
  • wp_template_part: The template parts to include in your templates.
  • wp_global_styles: The styles created and saved by the site adminadmin (and super admin) for the current theme.
  • wp_navigation: The navigation menus that can be inserted into the site.

Additional 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 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. will be published to introduce the new full site editing experience. Note the above post types are reserved terms for WordPress internal usage.

Thanks @mkaz for proofreading.

#5-9, #dev-notes

Editor Chat Agenda: 12 January 2021

Facilitator and notetaker: @jorgefilipecosta

This is the agenda for the weekly editor chat scheduled for Wednesday, January 12 2021, 03:00 PM GMT+1.

This meeting is held in the #core-editor channel in the Making WordPress SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/..

If you are not able to attend the meeting, you are encouraged to share anything relevant for the discussion:

  • If you have an update for the main site editing projects, please feel free to share as a comment or come prepared for the meeting itself.
  • If you have anything to share for the Task Coordination section, please leave it as a comment on this post.
  • If you have anything to propose for the agenda or other specific items related to those listed above, please leave a comment below.

#agenda, #core-editor, #core-editor-agenda, #meeting

Discussion: 2022 Major Release Timing

I mentioned in #core last week that it’s high time we talk about targets for major releases of WordPress next year. There are a few clear options, but there is at least one release we know about for sure! Given that we have a release in January already, I wonder if we might be able to use 2022 to attempt four releases.

Our Options

  • Quarterly releases: January, April, July, October
  • Trimester-ly releases: January, May, September
  • Known release and then evenly spaced targets?: January, May, August, November

I’d love to hear thoughts from both community members as well as our many contributors to the CMS itself. I’m planning to publish goals based on State of the WordState of the Word This is the annual report given by Matt Mullenweg, founder of WordPress at WordCamp US. It looks at what we’ve done, what we’re doing, and the future of WordPress. https://wordpress.tv/tag/state-of-the-word/. early in January, and would love to include this information there as well.

State of the Customizer with block themes in WordPress 5.9

With WordPress 5.9 bringing support for block themes, this results in a few changes to how the CustomizerCustomizer Tool built into WordPress core that hooks into most modern themes. You can use it to preview and modify many of your site’s appearance settings. works and how one can preview themes.

At a high level, this post covers how 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. themes cannot be previewed due to the introduction of the Site Editor and how the Customizer itself will only appear if a non-block theme is activated or a site has 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 that interacts with the Customizer.

Previewing block themes

If you activate a non-block theme like Twenty Twenty-One, open the Customizer, and click on the Change button in the Active theme section, you will see a warning message displayed for each block theme. Please see the example below:

A warning message is displayed for each block theme in the Customizer

It is displayed because the Customizer doesn’t support block themes. They can be customized in the Site Editor instead.

As a result, to customize a block-based theme, you need to activate it first. If you’re concerned about doing so, it’s recommended that you set up a test site first to explore the theme.

Also, it is not possible to preview inactive block themes because the Site Editor only works with the currently activated block theme. This means that the Live Preview button is not displayed for inactive block themes.

Once the ability to preview any block theme in the Site Editor is implemented, it will be possible to enable the Live Preview button for block themes as well.

Previewing non-block themes

Previewing non-block themes works the same way as in WordPress 5.8. Nothing has changed here.

Customizer and block themes

WordPress removes the Customizer from the Appearance menu if a block theme is enabled. Why? Block themes are customizable within the Site Editor rather than the Customizer.

However, if any callback function is registered for the customize_register action, the Customize menu item will be added. This is necessary to ensure compatibility with plugins that still require the Customizer to be present in the Appearance menu.

Because the Customizer shows up conditionally, various links have been adjusted depending on the type of active theme to ensure a smooth user experience.

For example, if a block theme is activated, the link in the Welcome banner leads to the Site editor. However, if a non-block theme is active, it leads to the Customizer.

Summary

If you need to preview or edit a block theme, activate it first. Previewing non-block themes will continue to work the same way.

WordPress will only add the Customize menu item if a non-block theme is activated or a plugin interacts with the Customizer (please see the customize_register action).

TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. tickets: #54549 (warning messages for block themes in the Customizer), #54460 (change links depending on the type of active theme), #54337 (conditionally show the Customizer in the Appearance menu).


Props to @annezazu and @hellofromtonya for technical review and proofreading; props to @audrasjb for proofreading; props to @desrosj for providing general feedback on this post.

#5-9, #block-themes, #customize, #customizer, #full-site-editing

Proposal: Changes to JavaScript Coding Standards for Full Prettier Compatibility

I propose switching to the original version of the Prettier code formatting tool in the GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ project and updating it to the most recent 2.5 version. Consequently, we should apply the necessary changes to the existing WordPress JavaScript Coding Standards around spacing to respect Prettier’s capabilities.

Code formatting challenges

It’s worth reminding that this topic was discussed several times, beginning in 2017 when the initial exploration of using Prettier started with WordPress/gutenberg#2819. Throughout all that time, the Prettier maintainers didn’t change their mind about adding support for spaces between parens (()) and brackets ([]) despite many requests shared in prettier/prettier#1303 from users (including the WordPress community). That’s why we decided to apply the first batch of JavaScript Coding Standards revisions two years later to use the forked version of Prettier developed by developers at Automattic. It allowed us to remain aligned with the coding style conventions used for PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher in the WordPress codebase. In particular, to follow these rules:

Use spaces liberally throughout your code. “When in doubt, space it out.”

The WordPress JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. standards prefer slightly broader whitespace rules than the jQuery style guide. These deviations are for consistency between the PHP and JavaScript files in the WordPress codebase.

The issue is that we ended up with an outdated fork of Prettier in the Gutenberg project that didn’t get any updates for more than a year. The only motivation behind using a custom version of Prettier remains its additional functionality overriding formatting behavior for spaces around parens and brackets. In the meantime, there were three minor releases of Prettier with a long list of new features in the last year:

The Gutenberg project no longer uses only JavaScript for development. Some parts of the codebase use TypeScript, which we agreed upon a few months back. It means we can’t use improvements added for newer versions of the TypeScript language and potentially for future additions to the JavaScript language. A deprecation was also added to one of the config options we use in the shared Prettier config that the community uses. It turns out that it prevents using the @wordpress/prettier-config package with the most recent version of Prettier in 3rd party projects, as explained in WordPress/gutenberg#37516. Finally, we had multiple reports in WordPress/Gutenberg#21872 from the community members using @wordpress/scripts or @wordpress/eslint-plugin packages that the forked version of Prettier doesn’t install correctly in their projects. The good news is that switching to the original Prettier will resolve all of the above!

It quickly became noticeable that the automatic code formatting saves you so much time and energy when trying to keep a consistent coding style in the project. This is why we also started using Prettier to format other types of files it supports in the Gutenberg project, like 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., YAML, Markdown. We also consider doing the same for CSSCSS Cascading Style Sheets. and SCSS next.

RevisionsRevisions The WordPress revisions system stores a record of each saved draft or published update. The revision system allows you to see what changes were made in each revision by dragging a slider (or using the Next/Previous buttons). The display indicates what has changed in each revision. to JavaScript Coding Standards

I propose we apply all the necessary changes to the WordPress JavaScript Coding Standards to switch to the latest available version of Prettier (2.5 as of writing). The excerptExcerpt An excerpt is the description of the blog post or page that will by default show on the blog archive page, in search results (SERPs), and on social media. With an SEO plugin, the excerpt may also be in that plugin’s metabox. of the most significant revisions is included below.

-Some whitespace rules differ, for consistency with the WordPress PHP coding standards.
+Some whitespace rules differ, for consistency with the [Prettier](https://prettier.io) formatting tool.
-All new or updated JavaScript code will be reviewed to ensure it conforms to the standards, and passes JSHint.
+All new or updated JavaScript code will be reviewed to ensure it conforms to the standards, and passes [ESLint](https://eslint.org).
-Use spaces liberally throughout your code. “When in doubt, space it out.”
-Any ! negation operator should have a following space.*
+Any ! negation operator should not have a following space.
-Always include extra spaces around elements and arguments:
-array = [ a, b ]; 
-foo( arg );
-foo( 'string', object );
-foo( options, object[ property ] );
-foo( node, 'property', 2 );
-prop = object[ 'default' ];
-firstArrayElement = arr[ 0 ];
+Never include extra spaces around elements and arguments: 
+arg = [a, b]; 
+foo(arg);
+foo('string', object);
+foo(options, object[property]);
+foo(node, 'property', 2);
+prop = object['default'];
+firstArrayElement = arr[0];
-var i;
-
-if ( condition ) {
-   doSomething( 'with a string' );
-} else if ( otherCondition ) {
-    otherThing( {
-        key: value,
-        otherKey: otherValue
-    } );
-} else {
-    somethingElse( true );
-}
- 
-// Unlike jQuery, WordPress prefers a space after the ! negation operator.
-// This is also done to conform to our PHP standards.
-while ( ! condition ) {
-    iterating++;
-}
- 
-for ( i = 0; i < 100; i++ ) {
-    object[ array[ i ] ] = someFn( i );
-    $( '.container' ).val( array[ i ] );
-}
- 
-try {
-    // Expressions
-} catch ( e ) {
-    // Expressions
-}
+var i;
+
+if (condition) {
+	doSomething('with a string');
+} else if (otherCondition) {
+	otherThing({
+		key: value,
+		otherKey: otherValue,
+	});
+} else {
+	somethingElse(true);
+}
+ 
+while (!condition) {
+	iterating++;
+}
+
+for (i = 0; i < 100; i++) {
+	object[array[i]] = someFn(i);
+	$('.container').val(array[i]);
+}
+
+try {
+	// Expressions
+} catch (e) {
+	// Expressions
+}

You can preview the impact on the Gutenberg codebase on GitHubGitHub GitHub is a website that offers online implementation of git repositories that can can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged be the repository owner. https://github.com/ in the exploratory Pull Request. The same changes would impact the tooling recommended for 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. development like @wordpress/create-block and @wordpress/scripts.

When will a decision be made?

Let’s plan for making a decision three weeks from the date of publication of this post. That should give enough time for discussion and questions.

#coding-style, #codingstandards, #javascript

Using multiple stylesheets per block

Prior to WordPress 5.9, 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. could (but not required to) have a stylesheet attached to it. The way blocks could register a stylesheet was by adding a style and/or editorStyle string in their block.json file.

In WordPress 5.9 we’re enhancing that behavior to allow using multiple stylesheets to be registered for each block. This change can benefit both block developers and theme developers, further reducing the total page-weight by only loading styles for blocks that exist on a page.

Blocks will now be able to register multiple stylesheets, and load styles from other blocks when needed. Themes will be able to add styles on a per-block basis instead of loading monolithic stylesheets that are force-loaded anywhere. This has a greater impact on block themes where stylesheets loading is optimised based on the page & layout contents, but can also be used by classic themes.

Usage for block developers

The style and editorStyle properties inside a block.json file can now be either a string, or an array of strings. Each string can be the handle of a previously registered stylesheet, or a path relative to the block.json file’s path, prefixed with file:./.

If you already have a block that uses a string, you needn’t worry. Everything will continue to work as expected. This is not a breaking change as the values can be either an array or a string, to maintain backward-compatibility.

This allows for complex blocks to reuse styles they need from other blocks without the need to duplicate those styles. For example, the comment-form block in WordPress 5.9 doesn’t need to duplicate the button block’s styles, and can instead reuse these styles by adding them to the block.json file:

{
 	"style": [
		"wp-block-post-comments-form",
		"wp-block-buttons",
		"wp-block-button"
	]
}

The same applies to the editorStyle value: Block developers can now define an array of styles, using the same format as the style value.

Usage for theme developers

Theme developers can also register stylesheets on a per-block basis. This way, no unnecessary styles will be rendered on a page unless the block is rendered (assuming the theme is a block-theme, or has opted-in to load separate stylesheets in the case of classic themes).

To do that, a new wp_enqueue_block_style() function was introduced.

The wp_enqueue_block_style function

The wp_enqueue_block_style function accepts 2 arguments, both of which are required:

$block_name

(string, required)

The name of the block – including its prefix/domain. For example the block_name of the paragraph block is core/paragraph.

$args

(array, required)

The arguments are the same used in the wp_enqueue_style function:

$args = array(
	'handle' => 'my-theme-p-styles',
	'src'    => get_theme_file_uri( 'styles/blocks/paragraph.css' ),
	...
);

In addition to the default wp_enqueue_style arguments, you can also add a path argument. This will allow WordPress to inline small assets when possible – if the theme opts-in to that behavior.

Example

Registering an extra stylesheet for the site-title block from a theme:

add_action( 'after_setup_theme', function() {
	// Same args used for wp_enqueue_style().
	$args = array(
		'handle' => 'my-theme-site-title',
		'src'    => get_theme_file_uri( 'assets/blocks/site-title.css' ),
	);

	// Add "path" to allow inlining asset if the theme opts-in.
	$args['path'] = get_theme_file_path( 'assets/blocks/site-title.css' );

	// Enqueue asset.
	wp_enqueue_block_style( 'core/site-title', $args );
} );

WordPress 5.9 enhances the way stylesheets for blocks get loaded. Though these changes have not been ported to block scripts yet, in future releases we plan to sync the two APIs, so block scripts can take advantage of them as well.

props @gziolo for reviewing this post.

#dev-notes, #developer-documentation

Block themes, a new way to build themes in WordPress 5.9

WordPress 5.9 makes the official introduction to 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. themes in WordPress, which previously required the GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ 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 to work and prioritizes working with the latest Full Site Editing features. The new default theme, Twenty Twenty-Two, ships with WordPress 5.9 and is the very first default block theme, which makes it a beautiful reference theme to learn from.

If you aren’t ready for a block theme just yet, no worries – classic themes continue to exist and work as always. Keep in mind though that to use the latest and greatest with full site editing, you’ll need to use a block theme, which is tailored to the newest features coming to WordPress. If you’re a theme author, see if you can start to incorporate some of these latest features into your themes, like 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. or the template editor.

A collection of screenshots featuring the Twenty Twenty-Two theme

Overview

At a high level, block themes use blocks to define the templates that layout and structure your entire site. The new templates and template parts are defined in HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers., and use the custom styling offered through theme.json.

After enabling a block theme, a new menu item under Appearance called “Editor (betaBeta A pre-release of software that is given out to a large group of users to trial under real conditions. Beta versions have gone through alpha testing in-house and are generally fairly close in look, feel and function to the final product; however, design changes often occur as part of the process.)” will show. This editor unlocks the ability to visually edit your homepage, templates, and template parts allowing you to create more of what you want in more places.

Thanks to the new features block themes offer and the ability to edit your content directly, the CustomizerCustomizer Tool built into WordPress core that hooks into most modern themes. You can use it to preview and modify many of your site’s appearance settings. menu is hidden from the dashboard unless you’re using a plugin that requires it. Read this GitHub issue for additional context.

For any current block theme authors, please note that there are new, simplified directory names: The name for the directory containing template files will be templates, and the name for the directory containing template part files will be parts. The block- prefix was dropped from both.

Join the fun and submit your own block theme to the WordPress Theme directory using the full-site-editing 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.). Find the listing of available block themes here: https://wordpress.org/themes/tags/full-site-editing/

Building block themes

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 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. cannot cover completely how to build a block theme, but here are some pointers to the documentation and reference to get you started.

First off, WordPress 5.9 ships with a beautiful block theme, TwentyTwentyTwo. Look in your theme directory or browse the GitHub repo to review the source and see what a block theme looks like.

The theme-experiments repository has an Empty Theme that is a good boilerplate to start your first block theme from. There is also a command-line script to help generate a block theme to get you started:

git clone https://github.com/WordPress/theme-experiments
cd theme-experiments
php new-empty-theme.php

Follow the prompts to create your theme and then copy the generated folder to your wp-content/themes directory.

Block theme documentation

Theme blocks

Explore building with Theme blocks a set of special blocks included for full site editing and block themes. Theme blocks are dynamic blocks that pull in content similar to the template tag functions from PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher, for example the Post Title block mirrors the the_title() function.

Here are two examples using theme blocks in a block templates. A singular post template (singular.html) is loaded with the post data, so using a theme blocks can be used stand-alone, for example:

<!-- wp:template-part {"slug":"header","tagName":"header"} /-->

<!-- wp:post-title /-->

<!-- wp:post-content {"layout":{"inherit":true}} /-->

When using theme blocks on an index or archive page, the theme blocks are used inside a Query LoopLoop The Loop is PHP code used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page, and formats it according to how it matches specified criteria within The Loop tags. Any HTML or PHP code in the Loop will be processed on each post. https://codex.wordpress.org/The_Loop. and Post Template, for example:

<!-- wp:template-part {"slug":"header","tagName":"header"} /-->

<!-- wp:query {"queryId":1,"query":{"offset":0,"postType":"post","categoryIds":[],"tagIds":[],"order":"desc","orderBy":"date","author":"","search":"","sticky":""}} -->
   <!-- wp:post-template -->
       <!-- wp:post-title {"isLink":true} /-->
       <!-- wp:post-excerpt /-->
   <!-- /wp:post-template -->
<!-- /wp:query -->

A pattern block can be used to insert translatable content inside a block template, since patterns are PHP-based, there is a mechanism to mark strings for translationtranslation The process (or result) of changing text, words, and display formatting to support another language. Also see localization, internationalization. or supply dynamic URLs. See the internationalization documentation


Props to @annezazu for contributing and reviewing this post.

#5-9, #dev-notes