From 244e4d4e637faa90d24a830690671064bb3fb48a Mon Sep 17 00:00:00 2001 From: Timothy Jacobs Date: Sun, 17 Jan 2021 00:49:39 +0000 Subject: [PATCH] REST API: Allow sending an empty array to delete multi meta keys. Previously, only `null` was supported. Fixes #50790. Props chrisvanpatten. git-svn-id: https://develop.svn.wordpress.org/trunk@49966 602fd350-edb4-49c9-b593-d223f7449a82 --- .../fields/class-wp-rest-meta-fields.php | 8 +++--- .../tests/rest-api/rest-post-meta-fields.php | 25 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php b/src/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php index 81806e1b65..78cef6f910 100644 --- a/src/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php +++ b/src/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php @@ -145,11 +145,15 @@ abstract class WP_REST_Meta_Fields { continue; } + $value = $meta[ $name ]; + /* * A null value means reset the field, which is essentially deleting it * from the database and then relying on the default value. + * + * Non-single meta can also be removed by passing an empty array. */ - if ( is_null( $meta[ $name ] ) ) { + if ( is_null( $value ) || ( array() === $value && ! $args['single'] ) ) { $args = $this->get_registered_fields()[ $meta_key ]; if ( $args['single'] ) { @@ -172,8 +176,6 @@ abstract class WP_REST_Meta_Fields { continue; } - $value = $meta[ $name ]; - if ( ! $args['single'] && is_array( $value ) && count( array_filter( $value, 'is_null' ) ) ) { return new WP_Error( 'rest_invalid_stored_value', diff --git a/tests/phpunit/tests/rest-api/rest-post-meta-fields.php b/tests/phpunit/tests/rest-api/rest-post-meta-fields.php index e3fc92d761..2b24cfc667 100644 --- a/tests/phpunit/tests/rest-api/rest-post-meta-fields.php +++ b/tests/phpunit/tests/rest-api/rest-post-meta-fields.php @@ -1027,6 +1027,31 @@ class WP_Test_REST_Post_Meta_Fields extends WP_Test_REST_TestCase { $this->assertSame( $post_original->post_content, $post_updated->post_content ); } + /** + * @ticket 50790 + */ + public function test_remove_multi_value_with_empty_array() { + add_post_meta( self::$post_id, 'test_multi', 'val1' ); + $values = get_post_meta( self::$post_id, 'test_multi', false ); + $this->assertSame( array( 'val1' ), $values ); + + $this->grant_write_permission(); + + $data = array( + 'meta' => array( + 'test_multi' => array(), + ), + ); + $request = new WP_REST_Request( 'POST', sprintf( '/wp/v2/posts/%d', self::$post_id ) ); + $request->set_body_params( $data ); + + $response = rest_get_server()->dispatch( $request ); + $this->assertSame( 200, $response->get_status() ); + + $meta = get_post_meta( self::$post_id, 'test_multi', false ); + $this->assertEmpty( $meta ); + } + public function test_remove_multi_value_db_error() { add_post_meta( self::$post_id, 'test_multi', 'val1' ); $values = get_post_meta( self::$post_id, 'test_multi', false );