Make WordPress Core


Ignore:
Timestamp:
07/07/2020 08:45:55 PM (4 years ago)
Author:
TimothyBlynJacobs
Message:

REST API, Meta: Introduce support for default metadata values.

The register_meta() API now officially supports specifying a default metadata value. When get_metadata() is called for a meta key that does not yet exist for the object, this default value will be returned instead of an empty string.

A new function is introduced get_metadata_raw to retrieve the raw metadata value from the database, without applying the registered default.

Props spacedmonkey, flixos90, rmccue, kadamwhite, mnelson4, johnbillion, chrisvanpatten, TimothyBlynJacobs.
Fixes #43941.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/rest-api/rest-term-meta-fields.php

    r46586 r48402  
    12571257
    12581258    /**
     1259     * @ticket 43941
     1260     */
     1261    public function test_get_default_value() {
     1262        $meta_key = 'registered_key1';
     1263        register_term_meta(
     1264            'category',
     1265            $meta_key,
     1266            array(
     1267                'single'       => true,
     1268                'type'         => 'string',
     1269                'default'      => 'Goodbye',
     1270                'show_in_rest' => true,
     1271            )
     1272        );
     1273
     1274        // Check for default value.
     1275        $request  = new WP_REST_Request( 'GET', sprintf( '/wp/v2/categories/%d', self::$category_id ) );
     1276        $response = rest_get_server()->dispatch( $request );
     1277
     1278        $this->assertEquals( 200, $response->get_status() );
     1279
     1280        $data = $response->get_data();
     1281        $this->assertArrayHasKey( 'meta', $data );
     1282
     1283        $meta = (array) $data['meta'];
     1284        $this->assertArrayHasKey( $meta_key, $meta );
     1285        $this->assertSame( 'Goodbye', $meta[ $meta_key ] );
     1286    }
     1287
     1288    /**
    12591289     * Internal function used to disable an insert query which
    12601290     * will trigger a wpdb error for testing purposes.
Note: See TracChangeset for help on using the changeset viewer.