Registering default values for meta data

With WordPress 5.5, the register_meta() functions ( including register_post_meta() ) now support registering default values. Previously it was only possible to register default values for 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/. schema like this:

register_meta(
     'post',
     'greeting',
     array(
         'single'       => true,
         'type'         => 'string',
         'show_in_rest' => array(
             'schema' => array(
                 'type'  => 'string',
                 'default' => 'hello',
             ),
         ),
     )
 );

However, this would only be applied to calls made from within the REST API – calls to get_post_meta() would not use this default value. Now it is possible to pass in a default value that will be applied to all calls to any of the 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. functions, like this:

register_meta(
     'post',
     'greeting',
     array(
         'single'       => true,
         'type'         => 'string',
         'default'      => 'hello',
         'show_in_rest' => array(
             'schema' => array(
                 'type'  => 'string',
             ),
         ),
     )
 );

This brings register_meta() inline with register_setting() where it has been possible to register default values for options since WordPress 4.7.

Default values can also be paired with object sub types (introduced in WordPress 4.9.8) to limit the scope of a default value. An example of this might be if 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 registers a 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. of product. A developer could register a default value that would only apply to the post of type product.

register_post_meta(
     'product',
     'price',
     array(
         'single'       => true,
         'type'         => 'string',
         'default'      => '0.00',
     )
 );

It is worth noting that registering a default value to a custom post type like this may have some performance overhead. To determine which post type the current post ID is, it has to load that object. See get_object_subtype for more detail. In most cases, the meta and main objects are loaded at the same time (like when using WP_Query) but if your code is doing something other than just loading meta data, it may now load the main object type too.

Non-Single Metadata

It is also possible to register not-single default values like this:

register_post_meta(
     'product',
     'price',
     array(
         'single'       => false,
         'type'         => 'string',
         'default'      => '0.00',
     )
 );

When requesting multiple values, like this:

$result = get_post_meta( 123, 'price', false );

The above code will return a numeric array with 0.00, as the first value.

Validation

When registering a default meta value the data must match the type provided. The following example will trigger a _doing_it_wrong notice as hello is not an integer.

register_meta(
     'post',
     'greeting',
     array(
         'single'       => true,
         'type'         => 'integer',
         'default'      => 'hello',
     )
 );

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.

If you desire to do some really custom with default meta values, there is now a filter:

$value = apply_filters( "default_{$meta_type}_metadata", $value, $object_id, $meta_key, $single, $meta_type );

This is a dynamic filter, requiring you to add the meta type. This is an example of it’s use:

function add_my_meta_value( $value, $object_id, $meta_key, $single ){
	if( 'price' === $meta_key ) {
		if ( ! $single ) {
	   		$value = array( '0.99' );
		} else {
			$value = '0.99';
		}
	}
}
add_filter( 'default_post_metadata', 'add_my_meta_value', 10, 4 );

New functions

To make this functionality possible there are two new functions added to WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.:

  • get_metadata_raw()
  • get_metadata_default()

Now the get_metadata() function calls get_metadata_raw() and if the value is null, calls get_metadata_default(). So calling get_metadata() no longer gets the raw value, that is what get_metadata_raw() is now intended for.

More detail of the history of this change can be found in the original tracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. ticketticket Created for both bug reports and feature development on the bug tracker. #43941.

Props @timothyblynjacobs, @jjj and @justinahinon for reviewing prior to publish.

#5-5, #dev-notes, #rest-api