Skip to content

Commit bcd149c

Browse files
committed
REST API: Make sure the class_list property is a list
1 parent 682f534 commit bcd149c

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2101,7 +2101,7 @@ public function prepare_item_for_response( $item, $request ) {
21012101
}
21022102

21032103
if ( rest_is_field_included( 'class_list', $fields ) ) {
2104-
$data['class_list'] = get_post_class( array(), $post->ID );
2104+
$data['class_list'] = array_values( get_post_class( array(), $post->ID ) );
21052105
}
21062106
}
21072107

tests/phpunit/tests/rest-api/rest-posts-controller.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2775,6 +2775,35 @@ public function test_prepare_item_override_excerpt_length() {
27752775
);
27762776
}
27772777

2778+
/**
2779+
* Test that the `class_list` property is a list.
2780+
*
2781+
* @ticket 64247
2782+
*
2783+
* @covers WP_REST_Posts_Controller::prepare_item_for_response
2784+
*/
2785+
public function test_class_list_is_list() {
2786+
$post_id = self::factory()->post->create();
2787+
2788+
// Filter 'post_class' to add a duplicate, which should be removed by `array_unique()`, causing a non-indexed array.
2789+
add_filter(
2790+
'post_class',
2791+
function ( $classes ) {
2792+
return array_merge(
2793+
array( 'duplicate-class', 'duplicate-class' ),
2794+
$classes,
2795+
);
2796+
}
2797+
);
2798+
2799+
$request = new WP_REST_Request( 'GET', '/wp/v2/posts/' . $post_id );
2800+
$response = rest_do_request( $request );
2801+
$data = $response->get_data();
2802+
2803+
$this->assertTrue( isset( $data['class_list'] ) );
2804+
$this->assertTrue( array_is_list( $data['class_list'] ) );
2805+
}
2806+
27782807
public function test_create_item() {
27792808
wp_set_current_user( self::$editor_id );
27802809

0 commit comments

Comments
 (0)