Cron API changes in WordPress 5.1

WordPress 5.1 sees a number of developer focused changes to the Cron 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.. These changes were discussed and made in #21072, #32656, #45797, and #45976.

Meaningful return values

Prior to WordPress 5.1, the functions used to modify scheduled tasks would return ambiguous values. These now return values indicating whether the function call was successful or otherwise.

wp_schedule_single_event(), wp_schedule_event(), wp_reschedule_event() and wp_unschedule_event() each return true or false to indicate whether the cron schedule was successfully modified.

wp_clear_scheduled_hook() and wp_unschedule_hook() each return false if the update was unsuccessful, 0 if there were no events to unschedule or an integer indicating the number of events that were successfully deleted.

Return values have also been added to the functions predominantly for use by WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. only: spawn_cron(), wp_cron(), and _set_cron_array().

New Functions

Two new functions have been added to assist with returning data.

wp_get_ready_cron_jobs(): retrieve cron jobs ready to be run.

Returns the results of _get_cron_array() limited to events ready to be run, ie, with a timestamp in the past. The new function returns the data only, it does not cause them to be run; that remains the role of other functions.

This function does not accept any arguments.

For more information, check out the source code for this function.

wp_get_scheduled_event(): retrieve a scheduled event.

Returns the full event object for a scheduled event.

The new function accepts three arguments:

  • $hook (string) Required, the action hook of the event.
  • $args (array) Optional. An array containing each separate argument to pass to the hook’s callback function.
  • $timestamp (integer or null) Optional. Unix timestamp (UTC) of the event. If not specified, the next scheduled event is returned.

The return value will be either the event object or false if the specified event has not been registered.

For more information, check out the source code for this function.

New filters for modifying cron storage

WordPress Core stores all cron events as an array in a single option. As the number of events increases, this method of storage can become somewhat unwieldy and unperformant.

In WordPress 5.1 writing a custom storage system for cron events will become substantially easier with filters added to each of the functions used for scheduling, re-scheduling, cancelling and returning a list of events.

Each of these 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. follows the pattern of bypassing the Core function if the 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. returns a value other than null.

Unless you are writing your own system for storing Cron jobs, these hooks are best left unused. If you are writing a custom storage solution, you will need to use all of them.

Each hook can be used to hijack the following:

  • pre_schedule_event for both single and recurring events,
  • pre_reschedule_event for rescheduling an event,
  • pre_unschedule_event for unscheduling an event
  • pre_clear_scheduled_hook for unscheduling all events attached to a hook/argument combination
  • pre_unschedule_hook for unscheduling all events related to a hook
  • pre_get_scheduled_event for returning an event including by specifying its timestamp,
  • pre_get_ready_cron_jobs for returning all cron events that are ready to be run

Warning: Adding code to these hooks must be done very early, before any other plugins attempt to register cron events or WordPress attempts to run any scheduled cron events on the init action.

Therefore, it is recommended you run add_filter() as your 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 included , rather than waiting for the plugins_loaded or muplugins_loaded actions to fire. For example:

// File name: my-cron-plugin/my-cron-plugin.php

// Bootstrap immediately.
add_filter( 'pre_schedule_event', 'mcp_schedule_event', 10, 2 );

/**
 * Use custom storage solution for scheduling Cron jobs.
 */
function mcp_schedule_event( $hijack, $event ) {
    if ( $hijack !== null ) {
        // Already hijacked.
        return $hijack;
    }

    // Use my plugin's custom storage solution.

    return true; // or false.
}

Note: WordPress 5.1 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 and 2 included the filters pre_next_scheduled and next_scheduled in the function wp_next_scheduled(). These were later removed as the logic for returning the next scheduled event was moved to wp_get_scheduled_event() to improve performance.

#5-1, #dev-notes

REST API Meeting Agenda for January 24, 2019

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/. team is taking inspiration from the 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/. team and will be posting Agenda documents ahead of the meeting as Google Docs so that agenda items can be gathered from a wider and more diverse group.

All agenda items are welcome, from all teams and contributors; please post them as suggestions on this document.

This meeting will be at January 24, 2019 18:00UTC; note that this is one hour later than the last few weeks, after discussion with regular participants. As component maintainers we acknowledge there is no perfect time, but please leave a note below or feel free to contact us if this change negatively affects your ability or inclination to participate in the chat.

#agenda, #rest-api

Privacy Office Hour Notes: January 16, 2019

The following is a summary of the weekly Privacy office hours that occurred on January 16, 2019. A full transcript can be found here in the #core-privacy room in the Make WordPress Slack.

Attendees: @desrosj, @garrett-eclipse, @dejliglama, @postphotos.

Here are the highlights of the meeting:

WordPress 5.1 Related Items

The full WordPress 5.1 release schedule can be found here

  • At the time of the meeting, 9 privacy component or focus tickets had been committed for release in 5.1 on February 21, 2019.
  • There were 6 privacy component or focus tickets remaining in the 5.1 milestone that needed to be committed or punted by the 5.1 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. 2 release on Tuesday, January 21, 2019.
  • That list of 6 had been scrubbed the previous Monday (January 14).

Open Floor

  • @idea15 mentioned that @xkon and herself have volunteered to represent the privacy team as participants in the cross-CMS privacy group.
  • The discussion was reopened about expanding the Privacy component to a recognized team with more responsibilities. @postphotos had a discussion with @chanthaboune at WCUS. The main suggestion was to make sure office hour summaries and agendas are regularly posted. Clearer momentum and documentation, as well as a larger contributor base, are also huge pluses.
  • Moving forward in the near term, new privacy features are going to be developed as plugins so they can be quickly iterated on and improved. Bug fixes to existing privacy features in WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. and newly discovered issues that need to be addressed can continue to take place in TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress..
  • @garrett-eclipse mentioned that in some recent Trac gardening he marked a few tickets with the close keyword and would like second opinions. Those tickets are #43958, #44161, and #44464.
  • #45999 was created to explore removing the privacy adminadmin (and super admin) pointers added in 4.9.6.
  • Some attendees expressed that they were currently finding it difficult to find time to contribute. @desrosj suggested investigating better ways to divide parts of initiatives and tasks to ensure work continues even when time for contributing is inconsistent or uncertain.

The weekly privacy office hours are held every Wednesday at 19:00 UTC in the #core-privacy room in the Make WordPress Slack.

#core-privacy, #privacy

Miscellaneous Developer Focused Changes in 5.1

In WordPress 5.1, a handful of small developer-focused changes were made that deserve to be called out. Let’s take a look!

File Path Value For WP_DEBUG_LOG

WP_DEBUG_LOG is a constant that tells WordPress to enable or disable error logging. Its default value is false (no error logging). But, if it’s defined as true (or 1) in the wp-config.php file, site errors will be logged in the wp-content/debug.log file.

Starting in WordPress 5.1, WP_DEBUG_LOG will also accept a file path as a value allowing a custom error log to be defined. For example:

define( 'WP_DEBUG_LOG', '/srv/path/to/custom/log/location/errors.log' );

Here are a few things to keep in mind:

  • The directory must already exist and be writable by the web server’s user.
  • The file does not need to exist. It will be created once the first error occurs as long as the previous condition is met.

Reminder: Any values set to WP_DEBUG_LOG and WP_DEBUG_DISPLAY will be ignored unless WP_DEBUG is set to true.

For more information, see #18391.

Test Suite: New Test Config File Constant

When running PHPUnit tests, the WordPress test suite requires a wp-tests-config.php file to be present in order to run correctly. This file provides information similar to that provided by the wp-config.php file. This includes database information, site domain and title, etc. (see the wp-tests-config-sample.php file for more information). However, the test suite bootstrap file requires this file to be in one of two locations: the test directory (tests/phpunit), or the root of the develop repository.

Starting in WordPress 5.1, the WP_TESTS_CONFIG_FILE_PATH constant can now be added to the phpunit.xml configuration file to define a custom location for the wp-tests-config.php file.

<phpunit ...
	<php>
		<const name="WP_TESTS_CONFIG_FILE_PATH" value="/path/to/wp-tests-config.php" />
	</php>
</phpunit>

For more information, see #39734.

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 Action 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 WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. today, the plugins_loaded, network_plugins_loaded, and mu_plugins_loaded action hooks exist, but these hooks are only run after all plugins of their respective types have been loaded. There is no easy way to execute arbitrary code between each plugin being loaded or only after plugin X is loaded.

This makes it difficult for developers to conduct performance monitoring and debugging during this stage of the loading process. In WordPress 5.1, the following action hooks will be added:

  • plugin_loaded
  • network_plugin_loaded
  • mu_plugin_loaded

These hooks will fire after every plugin is loaded. Each action hook will pass one argument, the full path of the main plugin file.

Because these hooks are fired after every individual plugin is loaded, they are not recommended as a replacement for plugins_loaded. Using them in this manner will cause issues with performance.

For more information, see #41346.

Short Circuit 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 wp_unique_post_slug()

When a post is created or updated, wp_unique_post_slug() is used to ensure that the post slug (post_name field) is unique to that post. By default, the function will add a numeric suffix to the desired post_name value and increment until a unique value is created (desired-slug-2, desired-slug-3, etc.).

In some scenarios (when post titles are the same and no post_name values are provided, for example), this can result in a performance bottleneck because a new query is performed every time the suffix is incremented until a unique value is created.

To help with this scenario, the pre_wp_unique_post_slug filter has been added in WordPress 5.1. If a non-null value is returned, the function will return that value and skip the default logic in the function. The new filter also opens the door for a handful of other use cases, such as always replacing certain terms in post names (changing wp to wordpress, for example).

For more information, see #21112.

Additional Developer Goodies

  • wp_debug_backtrace_summary() (which returns a list of functions called to get to the current point in the code) will now correctly capture hook names for do_action_ref_array() and apply_filters_ref_array() calls (see #43488). Previously, only do_action() and apply_filters() were captured.
  • $wpdb->queries logs the elapsed time for each query but lacks the starting time. This has been added in 5.1 (see #43315).
  • The WP_Error class now has a has_errors() method, which returns a boolean value indicating if an instance contains errors. This adds consistency to code that has previously checked for errors in a variety of ways, such as if ( $error->get_error_code() ) and if ( empty( $error->errors ) ) (see #42742).
  • A large number of inline documentation updates have been made to ensure accuracy proper formatting.

#5-1, #dev-notes

Dev Chat Agenda: January 23rd

Below is the agenda for the weekly devchat meeting on Wednesday, January 23, 2019 at 21:00 UTC:

  • 5.1 updates:
    • 5.1 Beta 2 was released and is now available for testing.
    • Schedule update.
    • 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. status report.
  • Updates from focus leads and component maintainers.
  • Open floor.

If you have anything to propose for the agenda or specific items related to those listed above, please leave a comment below.

This meeting is held in the #core channel in the Making WordPress Slack.

#5-1, #agenda, #core, #dev-chat

LIKE support for meta keys in 5.1

WordPress 5.1 introduces limited LIKEsupport for 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. keys when using WP_Meta_Query. The new compare_key parameter (meta_compare_key as a top-level WP_Query query arg) accepts a value of LIKE in addition to the default =. See #42409 and [42768]. Here’s an example of how the new parameter is used:

$q = new WP_Query(
  array(
    'post_type'  => 'my_custom_post_type',
    'meta_query' => array(
      array(
        'compare_key' => 'LIKE',
        'key'         => 'foo',
      ),
    ),
  )
);

This will generate a query of the form ... AND meta_key LIKE '%foo%' ....

This enhancementenhancement Enhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature. follows from changes in WordPress 4.8.3 to the way that MySQLMySQL MySQL is a relational database management system. A database is a structured collection of data where content, configuration and other options are stored. https://www.mysql.com/. wildcard characters are handled when building queries. The changes in 4.8.3 broke compatibility for some plugins that passed wildcards into the key parameter of meta queries. The new compare_keyfeature in WP 5.1 is not a full replacement for the previous behavior, but it should allow for most use cases. See #43445 for discussion.

#5-1, #dev-notes, #query

Improved taxonomy metabox sanitization in 5.1

WordPress 5.1 will feature a new parameter for register_taxonomy(), 'meta_box_sanitize_cb', which increases flexibility when using coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. UIUI User interface for custom taxonomies.

Custom taxonomies can specify which metaboxMetabox A post metabox is a draggable box shown on the post editing screen. Its purpose is to allow the user to select or enter information in addition to the main post content. This information should be related to the post in some way. UI they’d like to use in the Classic Editor by providing a meta_box_cb parameter when registering their taxonomies. This meant, for example, that a hierarchical 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. can choose to use the post_tags_meta_box() UI instead of post_categories_meta_box(), which is the default. Prior to 5.1, this customization wasn’t fully functional; while the UI could be swapped out in this way, the data submitted when saving posts was always processed according to whether the taxonomy was registered as hierarchical. This led to scenarios where custom taxonomy values weren’t properly parsed when saving a post.

In 5.1, this behavior is changed in the following ways:

  • The POST controller logic that was previously hardcoded in edit_post() has been abstracted into the new taxonomy_meta_box_sanitize_cb_checkboxes()and taxonomy_meta_box_sanitize_cb_input()functions.
  • WP will try to select an appropriate _sanitize_ callback based on the meta_box_cbassociated with the taxonomy. This will fix the underlying 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. for existing taxonomies.
  • Developers who need more control over the processing of their metabox data can provide a custom meta_box_sanitize_cb when registering their taxonomies.

For more information, see #36514 and [42211].

#5-1, #dev-notes, #taxonomy

JavaScript chat summary, January 22nd, 2019

Below is a summary of the discussion from this week’s 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/. chat (agendaSlack Transcript)

Have a topic for discussion for the next meeting? Leave a suggested edit on next week’s agenda.

Agenda: NPM Scripts

Slack Conversation

A few new commands have been proposed for addition to the @wordpress/scripts module:

  • build and start: https://github.com/WordPress/gutenberg/pull/12837
  • format: https://github.com/WordPress/gutenberg/pull/13394

The discussion around build and start focused mostly on the question how to approach default configuration for plugins and themes. We’re considering to extract parts of the Webpack config as npm package to simplify setup for 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 developers. This would also allow to provide a default config for @wordpress/scripts and proposed scripts. To provide flexibility, it was raised that an eventual Webpack config package could have 3 types of exports:

  • A full webpack config with a simple preset entries map for simple starter plugins ( front.js, admin.js, blocks.js or something like that ) to provide a simple zero-config option
  • A function that takes an entries map and outputs the full webpack config with recommended values.
  • Each part of the recommended config as their own keys.

The discussion provided good input for further iteration. Next, progress was shared on the format command, which aims to provide autoformatting functionality using Prettier and Eslint autofixers. It is still in an experimental state, but would provide a powerful tool for developers to more easily adhere to coding standards.

Agenda: Linting

Slack Conversation

We discussed the lack of ES2015+ rules in the WordPress JavaScript coding standards. A pull request was proposed on Gutenberg which makes using Object shorthand notation required for 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/ JavaScript. We agreed this was a desirable standard to have for ES2015+ code. For now, we decided to include the rule in the Gutenberg coding guidelines until a formal proposal to include ES2015+ rules in the WordPress JavaScript coding standards is drafted.

Agenda: E2E tests in coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.

Slack Conversation

Progress is being made on making Gutenberg’s e2e test functionality reusable for WordPress core and beyond. @gziolo gave the following status update:

  • Added package for Axe API integration with Jest and Puppeteer: https://github.com/WordPress/gutenberg/pull/13241. This is set of tools for accessibility static analysis which we want to integrate with e2e tests to ensure that we can catch regressions early on.
  • Extracted test utils to their own @wordpress/e2e-test-utils package: https://github.com/WordPress/gutenberg/pull/13228. It will allow some code reuse for those who would like to start writing e2e tests for their WordPress sites, plugins or themes.
  • Moved tests to their own @worpress/e2e-tests package: https://github.com/WordPress/gutenberg/pull/12465. There are now located in packages/e2e-tests/specs folder.

@gziolo plans to continue working on enabling a11y support to e2e tests in Gutenberg next. In order to start reusing the e2e setup in WordPress core, quite some configuration is still needed in WordPress core. This is tracked in https://core.trac.wordpress.org/ticket/45165. @adamsilverstein agreed to explore this further.

Agenda: PropTypes and ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/. Doc Generation

Slack Conversation

@ajitbohra proposed to add PropTypes to components in Gutenberg, in order to allow automated documentation generating and have type checking for components.

There was interest in the idea but also some concerns were raised:

  • There is some uncertainty of PropTypes’ future, considering that Facebook doesn’t use them and there exist other type systems which supersede them (Flow, TypeScript). PropTypes seems like a good solution for what we need right now, but in terms of type system, there might be better solutions available.
  • If they’re added, we need to make sure they are added as part of a proposal which also includes how they are going to be used, ie. for auto-documentation.

For now, we decided to avoid to add complexity without clearly understanding the merit. More exploration is needed on auto-documentation and the benefits of strong typing.

#core-js, #javascript, #meeting-notes, #summary

What’s New in Gutenberg? (23th January)

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/ 4.9 is a big milestone in terms for performance improvements for Gutenberg. It introduces a new asynchronous mode for blocks rendering improving the responsiveness of the editor.

The Documentation efforts are still on-going with three new tutorials leveraging the Format API, the Sidebar Plugins API and Post Meta Blocks as well as a number of improved README files for our UIUI User interface components.

In terms of developer experience, this release includes a lot of improvements to our e2e tests including support for aXe 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) testing.

Table 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. Stripes
Color Swatch Indicator

4.9 🇦🇺

Performance

Bug Fixes

Enhancements

Extensibility

Documentation

Chore

Mobile

#core-editor, #editor, #gutenberg