Customize Update – 2016-09-01

This is the weekly update post for the customize component. It includes a summary of this week’s meeting, recent commits, and next week’s meeting agenda.

Customize 4.7 Kickoff Meeting Summary

On Monday we held the customize component kickoff meeting in #core-customize on Slack [logs].

Potential 4.7 Projects

We started by identifying potential projects for 4.7, and people to lead them. The following projects are currently targeting merge for WordPress 4.7:

  • Create page-based nav menus without leaving live preview#34923 – @celloexpressions
    • @westonruter committed a first pass here, closing the primary ticketticket Created for both bug reports and feature development on the bug tracker. as fixed.
    • #37914, #37915, and #37916 have been created for follow up, and are currently in the 4.7 milestone. We need input from the 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. component to enable terms to be previewed before adding support for terms.
  • A new experience for themes in 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.#37661 – @celloexpressions
    • There are a few more dev-heavy tasks but we’re ready for design feedback (@folletto will take a look when he has time) and user testing.
    • In the coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. dev chat, @karmatosed volunteered to coordinate user testing here.
  • Code-editing gateways, via CSSCSS Cascading Style Sheets.#35395 – @johnregan3
    • We decided that bundling CSSTidy (used by Jetpack) in core is the best solution for sanitizing CSS.
    • Syntax highlighting for a more proper code-editing experience is a nice-to-have but not required for a first pass.
    • CSS should be stored in a new custom post typeCustom Post Type WordPress can hold and display many different types of content. A single item of such a content is generally called a post, although post is also a specific post type. Custom Post Types gives your site the ability to have templated posts, to simplify the concept. (with 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.), with a distinct post for each theme (i.e., all CSS will be theme-specific here).
    • @johnregan3 volunteered to spearhead this project and expects to have it ready for 4.7.
  • Customizer browser history #28536 – @westonruter
    • Development is happening on githubGitHub GitHub is a website that offers online implementation of git repositories that 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/, and there is only one issue currently, with customize-loader.js. We discussed potentially eliminating the 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. aspect of the customize loader script eventually, as it has caused a lot of issues and doesn’t offer significant usability benefits.
    • We also need to investigate possible performance issues in conjunction with #37661.
  • Customize snapshots/transactions #30937 – @westonruter
    • We decided that the snapshots UIUI User interface will remain in 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 for now, but transactions themselves could potentially be ready for 4.7. Transactions allow for the customizer to be used to preview changes to REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. in headless sites.
    • @westonruter brought up a few concerns with the sequencing of transaction updates and selective refresh, which could result in two HTTPHTTP HTTP is an acronym for Hyper Text Transfer Protocol. HTTP is the underlying protocol used by the World Wide Web and this protocol defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands. requests for the preview where there was previously one. Ensuring no degradation in performance is key here.
    • Transactions would complement #37661 nicely in 4.7 even without the snapshots UI, as theme customizations during the theme selection workflow could be saved without being published to the live site.
  • Customizer notifications #35210 – @westonruter
    • This needs more design feedback and a patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing. based on the latest proposal.
    • This is less of a project, so we’ll track it as a ticket moving forward.
  • Refactoring sliding panels UI#34391 – @delawski
    • @delawski will work to finish this up soon so that it can get into 4.7 relatively early.
    • We’ll need to coordinate this with the theme experience refresh in #37661, which bypasses the margin-top hacks.

Additional projects discussed:

  • Improve UI for linking preview elements to controls#27403
    • We might try to make some improvements here, but we aren’t currently targeting major changes for 4.7. This might change if more contributors contribute here, particularly on the design side.
  • Twenty Seventeen
    • @helen mentioned in the dev chat that information on Twenty Seventeen will be announced next week. Depending on the customize scope, we might want to have a dedicated person to help there and report back to the customize component meetings.
  • Customize Posts
    • Not targeting 4.7, but it would greatly benefit from a thorough UXUX User experience review now that the majority of the functionality is in place.
    • We’d like to fix #30378 in 4.7, using JS templates for the base WP_Customize_Control UI, to support the plugin.
    • A new project to bring similar functionality to taxonomy terms is breaking ground.
  • Live Preview Feature Project
    • After 4.7, we’ll revisit this project to take a holistic look at how live preview works in core. The end result will likely be a UX strategy for introducing contextual live preview for posts and terms, likely leveraging the existing customizer 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. and technology developed in the Customize Posts plugin, but potentially with an entirely different user interface than what’s currently known as the customizer: namely, looking at ways the customizer framework can be bootstrapped onto the frontend along with inline editing.

Additional Tickets Needing Attention

We briefly drew attention to the following tickets needing feedback from other teams:

  • Improving contrast and UI consistency in the customizer – #29158needs-testing
  • Improve custom background properties UI – #22058 – needs additional feedback on the latest proposals, and a patch
  • Appropriate means for themes to add top-level promotional links – #37335 – needs input from theme review team
    • The theme review team agreed that this was probably a good solution, but wants to investigate other options for developers before moving in this direction. On the core side, we’ll wait for direction from them

Open Floor

We closed with an open floor in lieu of a ticket scrub, due to time.

  • @clorith brought up sticky panel headers/back buttons (#34343 and #35186)
    • @delawski would like to work on these tickets after finishing #34391. We’ll need additional design feedback here as well to decide the direction (probably one or the other of the tickets).

Recent Customize Commits

Here are the customize-related commits for the past week:

  • [38396]: Customize: Circumvent the customizer attempting to preview links to static assets (such as uploaded images).
  • [38436]: Customize: Allow users to more seamlessly create page-based nav menus during customization.
  • [38464]: Customize: Improve handling of active state for dynamically-created controls/sections/panels.
  • [38478]: Customize: Use new `$status_code` parameter for `wp_send_json_error()` instead of calling `status_header()` separately.
  • [38479]: Customize: Fix i18ni18n Internationalization, or the act of writing and preparing code to be fully translatable into other languages. Also see localization. Often written with a lowercase i so it is not confused with a lowercase L or the numeral 1. Often an acquired skill. by re-using the `add_new_item` post type label instead of using a post type name in a generic string, in [38436].
  • [38492]: Customize: Introduce `paneVisible` state and ensure pane is visible when a construct is expanded (or focused).
  • [38503]: AccessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility): Make links in the Customizer underlined by default.

Big thanks to everyone who contributed to patches committed this week: @Presskopp, @afercia, @westonruter, @celloexpressions, @valendesigns, @melchoyce, @mapk, @iseulde, @mrahmadawais, @sayedwp, @johnbillion, and @curdin.

We’re always looking for more contributors; check out the open customize tickets and swing by #core-customize in 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/. to get involved.

Agenda for 2016-09-05 Meeting

We will have a meeting next week despite the holiday in the US; Monday, September 5 at 17:00 UTC. Agenda:

4.7 Projects

Additional Tickets Needing Attention

  • Improving contrast and UI consistency in the customizer – #29158needs-testing
  • Improve custom background properties UI – #22058 – needs additional feedback on the latest proposal, and a patch
  • Appropriate means for themes to add top-level promotional links – #37335 – needs input from theme review team
  • Customizer notfications – #35210 – needs UX feedback and a patch (and perhaps a clearer demonstration of the iteraction)

Ticket Scrub

  • Identify tickets ready for commit consideration, and 4.7 milestoning from future release tickets with a patch.
  • We’ll pick a different query to triagetriage The act of evaluating and sorting bug reports, in order to decide priority, severity, and other factors. each week. For example, bugs awaiting review (need verification).

We’ll see you next week!

#4-7, #customize

Customize Kickoff and Weekly Meetings for 4.7

We’ll be holding weekly meetings for the Customize component during the 4.7 cycle, to discuss both larger projects and smaller tickets needed attention. Meetings will be held on Mondays at 17:00 UTC in #core-customize and will last up to one hour, with additional continuous discussion happening throughout the week in the channel and in tickets.

The first meeting, on Monday, August 29th, will also serve as a kickoff for the customize efforts in 4.7, following up on yesterday’s general 4.7 kickoff.

Agenda for 2016-08-29 Meeting

The goal of this kickoff meeting will be to identify scope for 4.7 for the customize component. Most importantly, we need to identify larger projects that shouldn’t be considered for 4.7 (such as the customize posts project), so that we can prioritize those efforts that could get into 4.7 from now until 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. 1 hits. We will take some time to post any updates on future release projects each week.

Potential 4.7 Projects

  • Create page-based nav menus without leaving live preview – #34923
  • A new experience for themes in 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.#37661
  • Code-editing gateways, via CSSCSS Cascading Style Sheets.#35395
  • Customizer browser history#28536
  • Customizer notifications center – #35210
  • Customize snapshots/transactions#30937
  • Refactoring sliding panels UIUI User interface#34391
  • Improve UI for linking preview elements to controls – #27403
  • Twenty Seventeen – the customize team should be involved with the new theme, so that we can build any new coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. 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. that can facilitate it. Since default themes should be “state of the art”, let’s make sure that every option can be previewed instantly with postMessage, and fully supports selective refresh.

Active Future Release Project Updates

Additional Tickets Needing Attention

  • Improving contrast and UI consistency in the customizer – #29158needs-testing
  • Improve custom background properties UI – #22058 – needs additional feedback on the latest proposal, and a patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing.
  • Appropriate means for themes to add top-level promotional links – #37335 – needs input from theme review team

Ticketticket Created for both bug reports and feature development on the bug tracker. Scrub

  • Identify tickets ready for commit consideration, and 4.7 milestoning from future release tickets with a patch.
  • We’ll pick a different query to triagetriage The act of evaluating and sorting bug reports, in order to decide priority, severity, and other factors. each week. For example, bugs awaiting review (need verification).

We’re looking forward to seeing you at the meeting!

#4-7, #customize

Customize API Changes in 4.6

This post contains a summary of the developer-oriented changes and additions to the customize 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. in WordPress 4.6. View all 4.6 customize tickets here. The biggest new customize developer feature in 4.6 is setting validation, which has a dedicated post with details:

https://make.wordpress.org/core/2016/07/05/customizer-apis-in-4-6-for-setting-validation-and-notifications/

Clean up 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. Media Control CSSCSS Cascading Style Sheets. (#30618)

When the customizer media controls were modernized in WordPress 4.1, timeline considerations required the improvements to ship with a confusing and untenable markup structure and the resulting requirement to use separate CSS selectors for each sub-control of WP_Customize_Media_Control.

In 4.6, the markup of the coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. media controls has been simplified and the CSS completely refactored to allow media controls to share common CSS selectors. As a result, custom controls that use part of the core UIUI User interface and subclass WP_Customize_Media_Control no longer need to create their own CSS styles that duplicate core rules. Because the markup and styling has changed significantly, please test any custom controls, CSS, or 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/. that is related to media controls in the customizer.

Customize Value Hook Receives Context (#36452)

The customize_value_{$id_base} 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. now passes $this (the WP_Customize_Setting instance) as a second parameter, after the setting value. This provides access to all of the methods and parameters of the specific setting whose value is being filtered and brings this hook inline with the other 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. in WP_Customize_Setting.

Allow the Nav Menu Item Type Label (among other things) to be filtered (#35203)

The wp_setup_nav_menu_item filter is now applied consistently to all customizer settings representing nav menu items. The filter was previously used in WP_Customize_Nav_Menu_Item_Setting::value() but not in WP_Customize_Nav_Menu_Item_Setting::value_as_wp_post_nav_menu_item(), and is the same filter that’s used for the Menus screen in wp-adminadmin (and super admin).

Other Improvements

  • You can now use the Esc key to close the currently expanded section or panel (or widgetWidget A WordPress Widget is a small block that performs a specific function. You can add these widgets in sidebars also known as widget-ready areas on your web page. WordPress widgets were originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user./nav menu item control). See #22237.
  • The Custom Menu widget now includes a shortcut to edit a selected menu in the customizer. Navigating out of the nav menu section returns focus back to the Custom Menu widget where the shortcut button was clicked. See #32683.
  • When previewing a new theme in the customizer, clicking Activate will no longer result in being navigated out of the customizer and onto the frontend. See #35320.
  • The get_custom_logo filter now includes a blogblog (versus network, site) parameter. See #36639.
  • The menu locations section in the customizer now includes buttons to edit each selected menu. See #36795.
  • There is now a link to the widgets panel in the menu locations section description. See #36796.

#4-6, #customize, #dev-notes

Customizer APIs in 4.6 for Setting Validation and Notifications

As described in the Improving Setting Validation in the Customizer proposal post and detailed in #34893 and #36944, WordPress 4.6 includes new APIs related to validation of 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. setting values. The Customizer has had sanitization of setting values since it was introduced. Sanitization involves coercing a value into something safe to persist to the database: common examples are converting a value into an integer or stripping tags from some text input. As such, sanitization is a lossy operation.

But what happens in sanitization if a provided value is irrecoverable, beyond the ability to sanitize? The Customizer did allow sanitizers to return null in such cases which resulted in the value being skipped entirely from previewing and saving, but there was no feedback to the user that the value was skipped. Additionally, when multiple settings were modified but some were skipped due to returning null, the result was that a save operation would only persist the non-skipped settings to database: a user would unexpectedly find that only some of their settings were applied, resulting in an inconsistent saved state. Save operations were not transactional/atomic.

These are the problems that the Customizer setting validation improvements in WordPress 4.6 are designed to address. With setting validation:

  1. All modified settings are validated up-front before any of them are saved.
  2. If any setting is invalidinvalid A resolution on the bug tracker (and generally common in software development, sometimes also notabug) that indicates the ticket is not a bug, is a support request, or is generally invalid., the Customizer save request is rejected: a save thus becomes transactional with all the settings left dirty to try saving again. (The Customizer transactions proposal is closely related to setting validation here.)
  3. Validation error messages are displayed to the user, prompting them to fix their mistake and try again.

Sanitization and validation are also both part of the REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. infrastructure via WP_REST_Request::sanitize_params() and WP_REST_Request::validate_params(), respectively. A setting’s value goes through validation before it goes through sanitization (this is contrary to the original proposal, see #36944).

Validation Behavior

As noted above, if any setting is invalid, a Customizer save request is blocked. When save request is rejected due to setting invalidity, the controls that have the invalid setting will get the error notifications added to them, and one of these controls will be focused so that the user can correct the mistake. If there is an control with an invalid setting in the current section expanded, then this is the focus that will get the focus. Otherwise, the section containing an invalid control will get expanded and the control then focused.

Validation of setting values on the server does not only occur when a save is attempted. The setting values are validated and re-validated with each full refresh and selective refresh, and the their validity states are returned from the server in the responses. This means that setting validity will be reported in conjunction with updates to the preview. This is important for a couple reasons:

  1. When a setting is invalid, the previewed value will render using the previously-saved value or the default setting value, so the notification provides an explanation for why their changes aren’t appearing in the preview.
  2. As soon as a value is corrected and the preview request finishes, the error notification will be removed from the control. This means the user doesn’t have to try to saving to see whether the value has been corrected or not.

This second point has a key implication for validating settings that are previewed purely via 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/. (the postMessage transport without selective refresh): you should perform the validation logic for these using JavaScript as well. See client-side validation below.

Adding Validation to a Setting

Validate Callback

Just as you can supply a sanitize_callback when registering a setting, you can also supply a validate_callback arg:

$wp_customize->add_setting( 'established_year', array(
    'sanitize_callback' => 'absint',
    'validate_callback' => 'validate_established_year'
) );
function validate_established_year( $validity, $value ) {
    $value = intval( $value );
    if ( empty( $value ) || ! is_numeric( $value ) ) {
        $validity->add( 'required', __( 'You must supply a valid year.' ) );
    } elseif ( $value < 1900 ) {
        $validity->add( 'year_too_small', __( 'Year is too old.' ) );
    } elseif ( $value > gmdate( 'Y' ) ) {
        $validity->add( 'year_too_big', __( 'Year is too new.' ) );
    }
    return $validity;
}

Just as supplying a sanitize_callback arg adds 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. for customize_sanitize_{$setting_id}, so too supplying a validate_callback arg will add a filter for customize_validate_{$setting_id}. Assuming that the WP_Customize_Setting instances apply filters on these in their validate methods, you can add this filter if you need to add validation for settings that have been previously added.

The validate_callback and any customize_validate_{$setting_id} filter callbacks take a WP_Error instance is its first argument (which initially is empty of any errors added), followed by the $value being sanitized, and lastly the WP_Customize_Setting instance that is being validated.

Validate Method

A second way to add validation to a setting is by overriding the validate method on a WP_Customize_Setting subclass. For example:

class Established_Year_Setting extends WP_Customize_Setting {
    function validate( $value ) {
        if ( empty( $value ) || ! is_numeric( $value ) ) {
            return new WP_Error( 'required', __( 'You must supply a valid year.' ) );
        }
        if ( $value < 1900 ) {
            return new WP_Error( 'year_too_small', __( 'Year is too old.' ) ); 
        } 
        if ( $value > gmdate( 'Y' ) ) {
            return new WP_Error( 'year_too_big', __( 'Year is too new.' ) );
        }
        return true;
    }
}

Validating via Sanitization

The last way to add validation to a setting is to overload the sanitization routine to include validation as well. Setting sanitization and setting validation are closely related. Sanitization is for coercing/cleaning data. Validation is a pass/fail operation and is key to prevent data from being accepted when it is “too far gone” to be recovered from or when it is undesirable for the value to be silently and lossily cleaned. As noted above, setting’s sanitization logic can continue to return null and this will get interpreted as a setting’s value being invalid with a returned generic “Invalid value” error. You may also return a WP_Error instance from a sanitization routine which can be a handy way to consolidate the closely-related sanitization/validation logic; if you do this, make sure that you opt to return null in WP≤4.5, as otherwise this would result in a WP_Error instance being saved as a setting’s value (!!):

function sanitize_number( $value ) {
    $can_validate = method_exists( 'WP_Customize_Setting', 'validate' );
    if ( ! is_numeric( $value ) ) {
        return $can_validate ? new WP_Error( 'nan', __( 'Not a number' ) ) : null;
    }
    return intval( $value );
}

Again, this useful if you want to consolidate the closely-related logic into a single routine and also when to perform late validation after a value has been sanitized.

Client-side Validation

As noted above, if you have a setting that is previewed purely via JavaScript (and the postMessage transport without selective refresh), you should also add client-side validation as well. If you don’t then any validation errors will persist until a refresh happens or a save is attempted. Client-side validation must not take the place of server-side validation, since it would be trivial for a malicious user to bypass the client-side validation to save an invalid value if corresponding server-side validation is not in place.

There is actually already a validate method available on the wp.customize.Setting JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors. class (actually, the wp.customize.Value base class). It was introduced with the inception of the Customizer in WP 3.4, although I believe it has been rarely utilized. The validate method’s name is a bit misleading, as it actually behaves very similarly to the WP_Customize_Setting::sanitize() PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher method. Nevertheless, the method can be used to both sanitize and validate a value in JS. Note that this JS runs in the context of the Customizer pane not the preview, so any such JS should have customize-controls as a dependency (not customize-preview) and enqueued during the customize_controls_enqueue_scripts action. Some example JS validation:

wp.customize( 'established_year', function ( setting ) {
	setting.validate = function ( value ) {
		var code, notification;
		var year = parseInt( value, 10 );

		code = 'required';
		if ( isNaN( year ) ) {
			notification = new wp.customize.Notification( code, {message: myPlugin.l10n.requiredYear} );
			setting.notifications.add( code, notification );
		} else {
			setting.notifications.remove( code );
		}

		if ( isNaN( year ) ) {
			return value;
		}

		code = 'year_too_small';
		if ( year < 1900 ) {
			notification = new wp.customize.Notification( code, {message: myPlugin.l10n.yearTooSmall} );
			setting.notifications.add( code, notification );
		} else {
			setting.notifications.remove( code );
		}

		code = 'year_too_big';
		if ( year > new Date().getFullYear() ) {
			notification = new wp.customize.Notification( code, {message: myPlugin.l10n.yearTooBig} );
			setting.notifications.add( code, notification );
		} else {
			setting.notifications.remove( code );
		}

		return value;
	};
} );

Notifications 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.

An error notification is added to a setting’s notifications collection when a setting’s validation routine returns a WP_Error instance. Each error added to a PHP WP_Error instance is represented as a wp.customize.Notification in JavaScript:

  • A WP_Error‘s code is available as notification.code in JS.
  • A WP_Error‘s message is available as notification.message in JS. Note that if there are multiple messages added to a given error code in PHP they will be concatenated into a single message in JS.
  • A WP_Error‘s data is available as notification.data in JS. This is useful to pass additional error context from the server to the client.

Any time that a WP_Error is returned from a validation routine on the server it will result in a wp.customize.Notification being created with a type property of “error”.

While setting non-error notifications from PHP is not currently supported (see #37281), you can also add non-error notifications with JS as follows:

wp.customize( 'blogname', function( setting ) {
    setting.bind( function( value ) {
        var code = 'long_title';
        if ( value.length > 20 ) {
            setting.notifications.add( code, new wp.customize.Notification(
                code,
                {
                    type: 'warning',
                    message: 'Theme prefers title with max 20 chars.'
                }
            ) );
        } else {
            setting.notifications.remove( code );
        }
    } );
} );

You can also supply “info” as a notification’s type. The default type is “error”. Custom types may also be supplied, and the notifications can be styled with CSSCSS Cascading Style Sheets. selector matching notice.notice-foo where “foo” is the type supplied. A control may also override the default behavior for how notifications are rendered by overriding the wp.customize.Control#renderNotifications method.

Error notification

Warning notification

Info notification

custom-notification

More Examples

A couple plugins that make use of validation:

  • Customize Validate Entitled Settings: Demo that forces the site title, widgetWidget A WordPress Widget is a small block that performs a specific function. You can add these widgets in sidebars also known as widget-ready areas on your web page. WordPress widgets were originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user. titles, and nav menu labels to be populated with title case and lacking exclamations and questions.
  • Customize Posts: Validation errors added when posts would fail to save due to empty content, post locking, or save conflicts (with the specific conflicted fields being returned as WP_Error data). This 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 also features syncing back the server-sanitized setting values to upon save, something which I think should be in coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. at some point.
  • Standalone Customizer Controls: Demonstration of a controls used outside the Customizer with notifications added via JS based on HTML5 validity state.

Summary of API Changes

PHP changes:

  • Introduces WP_Customize_Setting::validate(), WP_Customize_Setting::$validate_callback, and the customize_validate_{$setting_id} filter.
  • Introduces WP_Customize_Manager::validate_setting_values() to do validation (and sanitization) for the setting values supplied, returning a list of WP_Error instances for invalid settings.
  • Attempting to save settings that are invalid will result in the save being blocked entirely, with the errors being sent in the customize_save_response. Modifies WP_Customize_Manager::save() to check all settings for validity issues prior to calling their save methods.
  • Introduces WP_Customize_Setting::json() for parity with the other Customizer classes. This includes exporting of the type.
  • Modifies WP_Customize_Manager::post_value() to apply validate after sanitize, and if validation fails, to return the $default.
  • Introduces customize_save_validation_before action which fires right before the validation checks are made prior to saving.

JS changes:

  • Introduces wp.customize.Notification in JS which to represent WP_Error instances returned from the server when setting validation fails.
  • Introduces wp.customize.Setting.prototype.notifications.
  • Introduces wp.customize.Control.prototype.notifications, which are synced with a control’s settings’ notifications.
  • Introduces wp.customize.Control.prototype.renderNotifications() to re-render a control’s notifications in its notification area. This is called automatically when the notifications collection changes.
  • Introduces wp.customize.settingConstructor, allowing custom setting types to be used in the same way that custom controls, panels, and sections can be made.
  • Injects a notification area into existing controls which is populated in response to the control’s notifications collection changing. A custom control can customize the placement of the notification area by overriding the new getNotificationsContainerElement method.
  • When a save fails due to setting invalidity, the invalidity errors will be added to the settings to then populate in the controls’ notification areas, and the first such invalid control will be focused.

#4-6, #customize, #dev-notes

Feature Proposal: Content Authorship in Menus, with Live Preview

The current navigation menus system is built around a paradigm that every menu item must be associated with an existing piece of content. However, this is problematic for new users, who may find themselves with the opportunity to build a menu before creating any content. #34923 seeks to improve this experience and eliminate this usability “dead end” by adding the ability to create new post objects (most notably pages) within the menus interface in 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..

content-authorship-nav-menus

Purpose & Goals

While this feature is aimed primarily at new users setting up their site for the first time, it may also be useful for users that are restructuring a site, or even if they want to add a page here or there and add it to their menu before filling out its contents. It’s important to note that posts and pages added here are stubs – only their title is filled out, and the content will be added later via the post editor. For that reason, most existing sites would probably maintain their existing workflows to create new pages via the post editor, publish them, and then add them to menus. This is of course still fully supported and the new proposal seeks to provide an alternative approach that may be better for different use cases such as new sites.

Because the feature is proposed to be located in the customizer, it also fully supports live preview. The live preview component can build user trust and confidence by letting users preview and interact with their site as changes are made, before they’re published.

Technical Considerations

To allow new content to be created in the customizer, posts are created with the auto_draft status. When the user saves & publishes in the customizer, these newly-created posts are transitioned to be published. In the customizer preview, the status is modified to protected to allow the posts to be previewed.

Ideally, term creation should also be a part of the menus UIUI User interface. Unfortunately, terms to not currently have a status field, and implementing that or looking at alternative approaches is something that will take more thought. Thus, this feature is being built with future support for terms in mind, but without support currently.

By default, the ability to add new content depends on the appropriate capabilities and the show_in_nav_menus parameter when registering post types. Additionally, a new 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. is proposed to allow authorship in menus to be disabled on a per-post-type basis.

Testing

User testing has been requested and there are several tasks that could be tested:

  • Create a new menu for a brand new site by creating pages and adding them to a menu, assign the menu to a location and publish it.
  • On an existing site, create new pages to add to an existing menu.
  • On a complex site with multiple menus create a new page once then add it to multiple menus.
  • On sites with custom post types, create new custom posts for any of the scenarios above.

Test with the latest patch on #34923 and make sure the customize posts 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 is not activated (it has conflicts). If anyone is able to conduct user tests that would be much appreciated.

Customize Posts Plugin

Part of the inspiration for this feature comes from the Customize Posts plugin, which has the ability to live-preview posts and post metaMeta Meta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress. in the customizer. Only a very small portion of the plugin would make its way into coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. as part of the nav menus content authorship feature. However, the proposal is currently to establish the wp.customize.Posts namespace for future expansions of post-related functionality in the customizer. The existing plugin would extend this core namespace, and other plugins could do so as well.

There are currently no plans to consider the Customize Posts plugin for full merge into core; however, stay tuned for an upcoming feature project kick-off that will seek to explore the future of live preview in WordPress at a broader level.

Feedback & Next Steps

The latest patch is currently seeking feedback for accessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility), design, code review, docs, and general comments. Please test it and leave your feedback as comments on this post or the ticketticket Created for both bug reports and feature development on the bug tracker., #34923. Given current timing the ticket is likely to target the 4.7 milestone.

One remaining piece to implement is a mechanism to inform the user that their new posts have been published and provide links to edit the posts in the adminadmin (and super admin). This could take the form of a notifications area in the customizer or preview, or happen inline within the menus UI as a notice using the customizer setting validation feature that’s new in 4.6. UXUX User experience feedback and ideas for the potential approach here are needed, and it could also probably work to ship without this part for now.

#customize, #menus, #proposal

Improving Setting Validation in the Customizer

In #34893 and the accompanying Customize Setting Validation feature pluginFeature Plugin A plugin that was created with the intention of eventually being proposed for inclusion in WordPress Core. See Features as Plugins. I’ve suggested improvements to 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. setting validation model. More can be read about the proposal in that ticketticket Created for both bug reports and feature development on the bug tracker. description and 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 readme, but the short of it is that settings in the Customizer generally undergo clean-up sanitization but lack a robust system for pass/fail validation. Here is a video demo depicting what I think validation should look like in the Customizer:

Normally the Customizer just sanitizes values by attempting to coerce them and clean them up into something that can be safely used (e.g. stripping tags). As for validation, and while I believe this is relatively unusual to encounter, you can also do strict validation of a setting by blocking it from being saved: this is done by returning null from WP_Customize_Setting::sanitize() (often via  WP_Customize_Setting::$sanitize_callback). This is the behavior for setting the background_color: if the value is not a valid hex code, it will not save. The problem here is that there is no feedback to the user that the save was blocked. If user tries to enter “blue” as a color instead of a hex code, they will not get informed that this is invalidinvalid A resolution on the bug tracker (and generally common in software development, sometimes also notabug) that indicates the ticket is not a bug, is a support request, or is generally invalid.: it will be as if they never tried to save any change at all. Incidentally, this is also the case for widgets, where the WP_Widget::update() normally just sanitizes the instance arrays, though it can return false 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. an update, with likewise no indication that the update was blocked.

Additionally, in the current validation system, if you have made 10 changes in your Customizer session (transaction), but half of them get blocked from saving due to being invalid, then you have an only partially-saved Customizer state. This is a really bad experience for sites that make heavy use of the Customizer beyond just using it to tweak some colors.

So to summarize the suggested improvements to validation in the customizer:

  1. All modified settings should be validated up-front before any of them are saved.
  2. If any setting is invalid, the Customizer save request should be rejected: a save thus becomes transactional with all the settings left dirty to try saving again.
  3. Validation error messages should be displayed to the user, prompting them to fix their mistake and try again.

All of the above is implemented in the Customize Setting Validation feature plugin, and I’d love your feedback on it. One thing in particular I need feedback on is how specifically a setting should go about performing validation on the server. As noted above, the WP_Customize_Setting::sanitize() method can currently do both sanitization (returning a cleaned-up value) and validation (returning null to block saving if value is beyond repair). In the current feature plugin, I’m proposing:

  1. Continue to use the same sanitize methods/callbacks/filters.
  2. Introduce a new $strict param to indicate that validation is being performed.
  3. Allow these functions to fail validation by returning WP_Error instances with information about what failed in addition to null as they can today.

Update 2016-06-26: The following examples differ from what has been committed to coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. A follow-up post will detail the new APIs for validation.

How the changes would look for WP_Customize_Setting::sanitize():

/**
 * Sanitize an input.
 *
 * @since 3.4.0
 * @since 4.6.0 Added `$strict` param to indicate validation is being performed.
 *
 * @param string|array $value  The value to sanitize.
 * @param bool         $strict Whether validation is being performed.
 * @return string|array|null|WP_Error Null or WP_Error if an input isn't valid, otherwise the sanitized value.
 */
public function sanitize( $value, $strict = false )

And for the customize_sanitize_{$id} 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.:

/**
 * Filter a Customize setting value.
 *
 * @since 3.4.0
 * @since 4.6.0 Added `$strict` param to indicate validation is being performed.
 *
 * @param mixed                $value  Value of the setting.
 * @param bool                 $strict Whether validation is being performed.
 * @param WP_Customize_Setting $this   WP_Customize_Setting instance.
 */
return apply_filters( "customize_sanitize_{$this->id}", $value, $this, $strict );

This should be nicely backwards-compatible, and allow for the sanitize/validate logic to be kept in the same function since they are very closely related. But that raises some questions:

  1. Should there be a separate WP_Customize_Setting::validate() method as well that by default calls WP_Customize_Setting::sanitize() with the $strict param set to true?
  2. Should validation only be applied when saving the setting while mere sanitization is required for previewing a value change?

On the second point here, my thought is that it may often be the desire for looser cleanup sanitization to be applied to a value during data entry. Consider a blob of text displayed on the page which forbids the use of markup. As I do data entry I may like to see what I am entering being displayed in the preview with the tags stripped (normal behavior today) whereas when I try saving I can be alerted that saving the value with markup is not allowed. This would provide the user with feedback as to why the markup is mysteriously not appearing in the preview. (As for providing this validation feedback while the user entering data, this should be done via JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors., or the validation state be determined by performing validation in an update-transaction request for transactions.)

I’ll also note that REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. supports both sanitization and validation for request args, but these are handled in two separate callbacks. The way it works is that any registered sanitize_callbacks are applied first, followed by setting of default values, and then the validate_callbacks are run. See WP_REST_Server::dispatch(). This works fine, but I think we could have more flexibility if the sanitization and validation logic could be in the same method. Perhaps you want to run sanitization before validation (sanitize by stripping tags and validate to ensure the value is not empty), or be more strict by running validation before sanitization (reject any text that contains markup entirely).

So, for you all who develop settings in the Customizer, what are your thoughts on how validation should behave, and how validation should relate to sanitization in the context of the Customizer? What do you think of the 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. changes I’ve proposed?

#4-6, #customize

Customize Office Hours Recap (May 2, 2016)

Early this week, @celloexpressions led a bugbug A bug is an error or unexpected result. Performance improvements, code optimization, and are considered enhancements, not defects. After feature freeze, only bugs are dealt with, with regressions (adverse changes from the previous version) being the highest priority. scrub for the Customize component which can be read in the chat logs. We did a bug scrub for the tickets milestoned for 4.6. Some highlights:

  • Transactions (#30937) is a high priority due to it resolving several other tickets. I (@westonruter) will try to make headway this week. Tickets impacted by this include (among others, since this a low-level architectural change for 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.):
    • #30028: Load Customizer preview 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. with natural URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org
    • #20714: Theme customizer: Impossible to preview a search results page
    • #23225: Customizer is Incompatible with jQuery UIUI User interface Tabs.
    • #31517: Customizer: show a notice after attempting to navigate to external links in live previews
    • #34142: Links with preventDefault() don’t have action prevented in Customizer
    • #28227: Customizer: Error message instead of blank screen
    • #31641: Theme Preview using “Customize.php” error
    • #22037: Customizer: Live preview fetches page but does not display
  • We discussed improvements to the Customizer setting validation model (#34893) and how they relate to transactions. I’ll be writing a separate Make CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. post to get feedback on it.
  • Global notification area and control-level notification areas were discussed. The global notification area (#35210) would be used for general Customizer notices/errors, such as fatal errors during save (#31582), whereas the notification are proposed for the in the setting validation model improvements (#34893) could be used for control-level notifications, like an error to uploading an image to a media control (#29932). Work is needed on the global notification area 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. and UI. Ideally the same API could be used at the control level, where there could be a wp.customize.notifications collection but also a wp.customize.control(...).notifications collection, both of which would be instances of the same NotificationCollection. Help wanted.
  • The customize_value_{$id_base} 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. now has the $setting object passed as the second param (#36452). The related ticketticket Created for both bug reports and feature development on the bug tracker. to add more actions/filters for implementing value and preview interfaces without subclassing WP_Customize_Setting (#29316) has been punted.
  • A new “Edit Menu” button for the Custom Menu widgetWidget A WordPress Widget is a small block that performs a specific function. You can add these widgets in sidebars also known as widget-ready areas on your web page. WordPress widgets were originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user. in Customizer (#32683) will get a new patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing. from @celloexpressions.
  • Simplification of the Customizer image control action buttons (#36175) needs some design/UXUX User experience feedback, and letting the image placeholder be clickable (#34323) was also discussed and also needs feedback.
  • Cleaning up the Customizer media control CSSCSS Cascading Style Sheets. (#30618) will get another patch from @celloexpressions this week.

We will be doing weekly meeting (office hours, triagetriage The act of evaluating and sorting bug reports, in order to decide priority, severity, and other factors., bug scrubs) at 20:00UTC on Mondays. See upcoming meetings for the next time.

#4-6, #customize

Customizer Kickoff for 4.6

This Monday, 18 April, 20:00 UTC we’ll have a 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. chat in #core-customize to discuss the roadmap and ideas for 4.6.

Referring to the Customizer roadmap post (and component page), at a high level, two big features I personally am interested in are:

A few other tickets that I’d love to see in this release, including some related tickets from the Widgets component:

  • #34893: Improve Customizer setting validation model
  • #34391: Harden panel/section UIUI User interface code by removing contents from being logically nested (read: goodbye margin-top hacks)
  • #29932: There is no error reporting in the Customizer
  • #35210: Add notification area to Customizer
  • #28216: Allow to register pre-instantiated widgets
  • #33507: Allow widgetWidget A WordPress Widget is a small block that performs a specific function. You can add these widgets in sidebars also known as widget-ready areas on your web page. WordPress widgets were originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user. controls to be JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors.-driven
  • #35574: Add REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. 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. schema information to WP_Widget

See also the Trac report for issues assigned to the 4.6 release, and then the tickets under future release and awaiting review.

Please share in the comments below if there are any specific features and tickets that you want to contribute in this next release to push the Customizer forward. Otherwise, please also join us in #core-customize chat to discuss.

Update: Read archive logs of meeting.

#4-6, #customize

Implementing Selective Refresh Support for Widgets

WordPress 4.5 includes a new 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. framework called selective refresh. To recap, selective refresh is a hybrid preview mechanism that has the performance benefit of not having to refresh the entire preview window. This was previously available with JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors.-applied postMessage previews, but selective refresh also improves the accuracy of the previewed change while reducing the amount of code you have to write; it also just makes possible to do performant previews that would previously been practically impossible. For example, themes often include some variation of the following PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher and 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/. to enable performant previewing of changes to the site title:

function mytheme_customize_register( WP_Customize_Manager $wp_customize ) {
	$wp_customize->get_option( 'blogname' )->transport = 'postMessage';
}
add_action( 'customize_register', 'mytheme_customize_register' );

function mytheme_customize_preview_js() {
	$handle = 'mytheme-customize-preview';
	$src = get_template_directory_uri() . '/js/customize-preview.js';
	$deps = array( 'customize-preview' );
	$ver = '0.1';
	$in_footer = true;
	wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
}
add_action( 'customize_preview_init', 'mytheme_customize_preview_js' );
( function( $, api ) {
	api( 'blogname', function( setting ) {
		setting.bind( function( value ) {
			$( '.site-title a' ).text( value );
		} );
	} );
} ( jQuery, wp.customize ) );

In 4.5, the coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. themes now utilize selective refresh for previewing the site title and tagline. This allows the above code to be replaced with the following PHP:

function mytheme_customize_register( WP_Customize_Manager $wp_customize ) {
	$wp_customize->selective_refresh->add_partial( 'blogname', array(
		'selector' => '.site-title a',
		'render_callback' => function() {
			bloginfo( 'name' );
		},
	) );
}
add_action( 'customize_register', 'mytheme_customize_register' );

So as you can see, not only is the amount of code more than cut in half (also eliminating the JS file altogether), it also ensures that when a site title change is previewed it will appear with all of the PHP filters applied from core and plugins: for example wptexturize will apply so that curly quotes and dashes will appear as expected. In REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. parlance, selective refresh enables the Customizer preview to show title.rendered instead of just title.raw. (For more on this change to previewing the site title and tagline, see #33738. The previous JS-based previewing is retained for an instant low-fidelity preview while the selective refresh request returns.) Selective refresh is also the mechanism used for previewing the new custom logo feature in 4.5, ensuring that the logo image is rendered re-using the image_downsize logic in PHP without having to re-implement it in JS (keeping the code DRY).

With that recap of selective refresh out of the way, let’s turn to the focus of this post: selective refresh for widgets. When widgetWidget A WordPress Widget is a small block that performs a specific function. You can add these widgets in sidebars also known as widget-ready areas on your web page. WordPress widgets were originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user. management was added to the Customizer in 3.9, every change to a widget required a full page refresh to preview. This resulted in a poor user experience since a full refresh can take awhile, especially on weighty pages. So selective refresh of widgets is a key usability experience improvement for widget management in the Customizer in 4.5. However, as live postMessage updates to the site title and tagline have required supporting theme code (see above), so too will theme support be required for widgets, as noted in the Selective Refresh of Widgets section from the previous post on this topic:

Selective refresh for nav menus was enabled by default in 4.3. While some themes needed to add theme support for any dynamic aspects (such as the expanding submenus in Twenty Fifteen), generally nav menus seem to be fairly static and can be replaced in the document without needing any JS logic to be re-applied. Widgets, on the other hand, have much more variation in what they can display, since they can in fact display anything. For any widget that uses JavaScript to initialize some dynamic elements, such as a map or gallery slideshow, simply replacing the widget’s content with new content from the server will not work since the dynamic elements will not be re-initialized. Additionally, the sidebars (widget areas) in which the widgets are displayed may also have dynamic aspects associated with them, such as the Twenty Thirteen sidebarSidebar A sidebar in WordPress is referred to a widget-ready area used by WordPress themes to display information that is not a part of the main content. It is not always a vertical column on the side. It can be a horizontal rectangle below or above the content area, footer, header, or any where in the theme. which displays widgets in a grid using Masonry. For this theme, whenever a widget is changed/added/removed/reordered, the sidebar needs to be reflowed.

In order to allow themes to reflow sidebars and widgets to reinitialize their contents after a refresh, the selective refresh framework introduces widget-updated and sidebar-updated events. Additionally, since re-ordering widgets in a sidebar is instant by just re-ordering the elements in the DOM, some widgets with dynamically-generated iframes (such as a Twitter widget) may need to also be rebuilt, and for this reason there is a partial-content-moved event.

For the above reasons, I believe it will be much more common for widgets (and sidebars) to need special support for selective refresh, and so I think that at least for 4.5 the selective refresh should be opt-in for widgets (and perhaps in themes for sidebars). See theme support for Twenty Thirteen and plugin support for a few widgets in Jetpack (which won’t be part of the merge). At last week’s Core dev meeting, it was suggested that we add the opt-in for widget selective refresh at RCrelease candidate One of the final stages in the version release cycle, this version signals the potential to be a final release to the public. Also see alpha (beta)..

So as noted, selective refresh for widgets will be opt-in as of 4.5 RC1 (see #35855).

What do themes and widgets need to do to opt-in for selective refresh support?

Selective refresh will be used for previewing a widget change when both the theme and the widget itself indicate support as follows:

Adding Theme Support

If your theme does not do anything fancy with its sidebars (such as using Masonry to lay out widgets), then all that you need to do is add the following to your theme:

add_theme_support( 'customize-selective-refresh-widgets' );

On the other hand, if the theme is rendering a sidebar in a unique way, then to add a bit of logic to handle the changes properly. For example, as noted previously the footer area in Twenty Thirteen consists of a sidebar that is laid out using Masonry. When a widget is added, removed, or updated, the Masonry logic needs to be re-run to update the positioning of the widgets in the sidebar. The following highlighted code is what handles this:

jQuery( function( $ ) {
	var widgetArea = $( '#secondary .widget-area' );
	widgetArea.masonry( {
		itemSelector: '.widget',
		columnWidth: columnWidth,
		gutterWidth: 20,
		isRTL: body.is( '.rtl' )
	} );
	
	if ( 'undefined' !== typeof wp && wp.customize && wp.customize.selectiveRefresh ) {
		wp.customize.selectiveRefresh.bind( 'sidebar-updated', function( sidebarPartial ) {
			if ( 'sidebar-1' === sidebarPartial.sidebarId ) {
				widgetArea.masonry( 'reloadItems' );
				widgetArea.masonry( 'layout' );
			}
		} );
	}
} );

Update 2016-07-17: Added the jQuery() DOM ready wrapper around this logic to ensure it runs after the DOM has been fully loaded, and thus ensuring the wp.customize.selectiveRefresh object exists if it is going to be loaded. See ​#37390 as this also turned out to be broken in Twenty Thirteen.

Note the if statement is there so the code will only run in the Customizer preview and if selective refresh is available (that is, if they are running 4.5 or later).

Adding Widget Support

If your widget lacks any dynamic functionality with JavaScript initialization, adding support just requires adding a customize_selective_refresh flag to the $widget_options param when constructing the WP_Widget subclass. If you are enqueueing any CSSCSS Cascading Style Sheets. for styling the widget, you’ll also want to enqueue this unconditionally in the Customizer preview (if is_customize_preview()) so that a widget can be added to the preview and be styled properly without doing a full page refresh. For example, note these highlighted lines in a sample widget:

class Example_Widget extends WP_Widget {

	public function __construct() {
		parent::__construct(
			'example',
			__( 'Example', 'my-plugin' ),
			array(
				'description' => __( 'Selective refreshable widget.', 'my-plugin' ),
				'customize_selective_refresh' => true,
			)
		);

		// Enqueue style if widget is active (appears in a sidebar) or if in Customizer preview.
		if ( is_active_widget( false, false, $this->id_base ) || is_customize_preview() ) {
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		}
	}

	public function enqueue_scripts() {
		wp_enqueue_style( 'my-plugin-example-widget', plugins_url( 'example-widget.css', __FILE__ ), array(), '0.1' );
	}

	/* ... */
}

On the other hand, as with sidebars in a theme, if a widget uses JavaScript for initialization, you’ll need to add logic to make sure re-initialization happens when the widget is selectively refreshed. So in addition to the above example, you must:

  1. Enqueue any dependent JS logic if is_customize_preview() just as noted above for enqueueing any CSS stylesheet.
  2. Add a handler for partial-content-rendered selective refresh events to rebuild a widget’s dynamic elements when it is re-rendered.
  3. As needed, add a handler for partial-content-moved selective refresh events to refresh partials if any dynamic elements involve iframes that have dynamically-written documents (such as the Twitter Timeline widget). (Adding this event handler should normally not be required.)

The Twitter Timeline widget in the Jetpack 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 is a good example for how to write these event handlers:

jQuery( function() {
	// Short-circuit selective refresh events if not in customizer preview or pre-4.5.
	if ( 'undefined' === typeof wp || ! wp.customize || ! wp.customize.selectiveRefresh ) {
		return;
	}

	// Re-load Twitter widgets when a partial is rendered.
	wp.customize.selectiveRefresh.bind( 'partial-content-rendered', function( placement ) {
		if ( placement.container ) {
			twttr.widgets.load( placement.container[0] );
		}
	} );

	// Refresh a moved partial containing a Twitter timeline iframe, since it has to be re-built.
	wp.customize.selectiveRefresh.bind( 'partial-content-moved', function( placement ) {
		if ( placement.container && placement.container.find( 'iframe.twitter-timeline:not([src]):first' ).length ) {
			placement.partial.refresh();
		}
	} );
} );

(This is adapted from a pending PR for Jetpack.)

Conclusion

All core themes and core widgets will have support for selective refresh in 4.5. Now it’s up to theme and plugin authors to also add support to also start taking advantage of these drastic performance improvements for previewing widget changes.

#4-5, #customize, #dev-notes, #feature-selective-refresh

Customizer Improvements in 4.5

In addition to the ~35 defects that were fixed in this release, there were also ~17 features and enhancements that were made. What follows are some highlights, starting with some smaller enhancements and then listing out full posts that document the larger features.

Setting-less Controls (#35926)

Sometimes controls need to be added which don’t directly have associated settings. For example, there can be controls needed which manipulate some aspect of 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. interface or manage the behavior of other controls and their settings: consider a control for managing repeating controls, where the button only serves to create other controls and their settings. When nav menus were added in the Customizer in 4.3, the UIUI User interface for creating a new menu involved two controls which had custom settings associated them (create_new_menu and new_menu_name) which served no purpose other than to make sure the control wouldn’t raise an error. The settings had custom types to prevent them from getting saved to the DB.

In 4.5, controls are no longer required to have associated settings. By default registering a control without an explicit settings argument will result in the control’s own id being supplied as the associated setting id. To explicitly register a control without any associated settings, pass an empty array as the settings:

$wp_customize->add_control( 'new-post', array(
	'section'  => 'title_tagline',
	'settings' => array(),
	'type' => 'button',
	'input_attrs'  => array(
		'value' => __( 'Add Post' ),
	),
	'capability' => 'edit_posts',
) );

Because controls no longer require settings, controls now accept a capability argument (as seen above) whereas previously a control’s capability would depend on the capabilities of its associated settings. A control will not be displayed if it has a defined capability which the user doesn’t have, or if the user doesn’t have the capability required for any of the associated settings. If you omit the capability for a setting-less control, it will be displayed to all users (who can customize).

Other Improvements

  • Shift-click on nav menu items in preview to open corresponding control in Customizer pane (#26005).
  • Shift-click on site title and tagline for CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. themes and any that implement selective refresh partials for these settings. Focus on the control for any setting in the preview by sending a focus-control-for-setting message to the pane, passing the setting ID. This is used to focus on controls when a shift-click is done on a selective refresh partial.
  • Site title and tagline will be updated via selective refresh in core themes. (#33738)
  • WP_Customize_Manager::add_*() methods now return the added instance. (#34596)
  • WP_Customize_Manager::add_setting() now applies the relevant dynamic setting filters. (#34597)
  • There is a new customize_nav_menu_searched_items 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. for nav menu item searches. (#34947)
  • The WP_Customize_Media_Control now allows its button_labels to be overridden. (#35542)
  • The setting models in the preview now have a id property and _dirty flag to correspond to the settings in the pane; dynamically created settings in the pane will be created in the preview. (#35616)
  • More config settings are exported to the preview to allow the preview to do more operations inline, including more nonces, the current theme, and the previewed URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org. (#35617)

Dedicated Feature Posts

Device Preview (#31195)

https://make.wordpress.org/core/2016/01/28/previewing-site-responsiveness-in-the-customizer/

Selective Refresh (#27355)

https://make.wordpress.org/core/2016/02/16/selective-refresh-in-the-customizer/

Custom Logo (#33755)

https://make.wordpress.org/core/2016/03/10/custom-logo/

#4-5, #customize, #dev-notes