Skip to content

Commit a59c400

Browse files
committed
REST API: Ensure empty meta is returned as an object in view context
1 parent 4d3b0b9 commit a59c400

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

src/wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,15 @@ public function filter_response_by_context( $data, $context ) {
5858
unset( $data['content']['rendered'] );
5959

6060
// Add the core wp_pattern_sync_status meta as top level property to the response.
61-
$data['wp_pattern_sync_status'] = $data['meta']['wp_pattern_sync_status'] ?? '';
62-
unset( $data['meta']['wp_pattern_sync_status'] );
61+
$meta = (array) $data['meta'];
62+
$data['wp_pattern_sync_status'] = $meta['wp_pattern_sync_status'] ?? '';
63+
64+
if ( is_object( $data['meta'] ) ) {
65+
unset( $data['meta']->wp_pattern_sync_status );
66+
} else {
67+
unset( $data['meta']['wp_pattern_sync_status'] );
68+
}
69+
6370
return $data;
6471
}
6572

src/wp-includes/rest-api/fields/class-wp-rest-meta-fields.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,8 @@ public function register_field() {
7474
*
7575
* @param int $object_id Object ID to fetch meta for.
7676
* @param WP_REST_Request $request Full details about the request.
77-
* @return array Array containing the meta values keyed by name.
77+
* @return array|object Array containing the meta values keyed by name,
78+
* or an empty object if to ensure JSON object encoding.
7879
*/
7980
public function get_value( $object_id, $request ) {
8081
$fields = $this->get_registered_fields();
@@ -105,6 +106,11 @@ public function get_value( $object_id, $request ) {
105106
$response[ $name ] = $value;
106107
}
107108

109+
// Use stdClass so that JSON result is {} and not [].
110+
if ( empty( $response ) ) {
111+
return (object) array();
112+
}
113+
108114
return $response;
109115
}
110116

@@ -582,6 +588,10 @@ public static function prepare_value( $value, $request, $args ) {
582588
* @return array|false The meta array, if valid, false otherwise.
583589
*/
584590
public function check_meta_is_array( $value, $request, $param ) {
591+
if ( is_object( $value ) ) {
592+
$value = (array) $value;
593+
}
594+
585595
if ( ! is_array( $value ) ) {
586596
return false;
587597
}

0 commit comments

Comments
 (0)