Using WordPress ‘rest_default_additional_properties_to_false()’ PHP function

The rest_default_additional_properties_to_false() WordPress PHP function sets the “additionalProperties” to false by default for all object definitions in the schema.

Usage

rest_default_additional_properties_to_false( $schema );

Parameters

  • $schema (array) – Required. The schema to modify.

More information

See WordPress Developer Resources: rest_default_additional_properties_to_false()

Examples

Modifying a REST API schema

Set “additionalProperties” to false for all object definitions in the schema.

// Define the schema
$schema = array(
  'type' => 'object',
  'properties' => array(
    'title' => array(
      'type' => 'string',
    ),
    'content' => array(
      'type' => 'string',
    ),
  ),
);

// Apply the rest_default_additional_properties_to_false() function
$modified_schema = rest_default_additional_properties_to_false( $schema );

Customizing a custom post type REST API schema

Customize the schema for a custom post type and set “additionalProperties” to false for all object definitions.

add_filter( 'rest_prepare_my_custom_post_type', 'my_custom_post_type_rest_prepare', 10, 3 );
function my_custom_post_type_rest_prepare( $response, $post, $request ) {
  $schema = $response->get_schema();
  $modified_schema = rest_default_additional_properties_to_false( $schema );
  $response->set_schema( $modified_schema );
  return $response;
}

Adding a custom field to a custom post type schema

Add a custom field to a custom post type schema and set “additionalProperties” to false for all object definitions.

add_filter( 'rest_prepare_my_custom_post_type', 'my_custom_post_type_add_custom_field', 10, 3 );
function my_custom_post_type_add_custom_field( $response, $post, $request ) {
  $schema = $response->get_schema();
  $schema['properties']['my_custom_field'] = array(
    'type' => 'string',
  );
  $modified_schema = rest_default_additional_properties_to_false( $schema );
  $response->set_schema( $modified_schema );
  return $response;
}

Customizing the schema for a taxonomy

Customize the schema for a taxonomy and set “additionalProperties” to false for all object definitions.

add_filter( 'rest_prepare_taxonomy', 'my_taxonomy_rest_prepare', 10, 3 );
function my_taxonomy_rest_prepare( $response, $taxonomy, $request ) {
  $schema = $response->get_schema();
  $modified_schema = rest_default_additional_properties_to_false( $schema );
  $response->set_schema( $modified_schema );
  return $response;
}

Customizing a user schema

Customize the schema for a user and set “additionalProperties” to false for all object definitions.

add_filter( 'rest_prepare_user', 'my_user_rest_prepare', 10, 3 );
function my_user_rest_prepare( $response, $user, $request ) {
  $schema = $response->get_schema();
  $modified_schema = rest_default_additional_properties_to_false( $schema );
  $response->set_schema( $modified_schema );
  return $response;
}