REST API: Avoid undefined-property notice when setting parent term to 0.

Only try to access `term_id` once `$parent_term` is known to be a `WP_Term`.

Props dlh, earnjam.
Fixes #44983.


git-svn-id: https://develop.svn.wordpress.org/trunk@44965 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
K. Adam White 2019-03-21 18:58:50 +00:00
parent 9a129eec78
commit 49d8c2590c
2 changed files with 47 additions and 4 deletions

View File

@ -685,11 +685,15 @@ class WP_REST_Terms_Controller extends WP_REST_Controller {
}
if ( isset( $request['parent'] ) && ! empty( $schema['properties']['parent'] ) ) {
$parent_term_id = 0;
$parent_term = get_term( (int) $request['parent'], $this->taxonomy );
$parent_term_id = 0;
$requested_parent = (int) $request['parent'];
if ( $parent_term ) {
$parent_term_id = $parent_term->term_id;
if ( $requested_parent ) {
$parent_term = get_term( $requested_parent, $this->taxonomy );
if ( $parent_term instanceof WP_Term ) {
$parent_term_id = $parent_term->term_id;
}
}
$prepared_term->parent = $parent_term_id;

View File

@ -859,6 +859,18 @@ class WP_Test_REST_Categories_Controller extends WP_Test_REST_Controller_Testcas
$this->assertErrorResponse( 'rest_term_invalid', $response, 400 );
}
public function test_create_item_with_no_parent() {
wp_set_current_user( self::$administrator );
$parent = 0;
$request = new WP_REST_Request( 'POST', '/wp/v2/categories' );
$request->set_param( 'name', 'My Awesome Term' );
$request->set_param( 'parent', $parent );
$response = rest_get_server()->dispatch( $request );
$this->assertEquals( 201, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( $parent, $data['parent'] );
}
public function test_update_item() {
wp_set_current_user( self::$administrator );
$orig_args = array(
@ -929,6 +941,33 @@ class WP_Test_REST_Categories_Controller extends WP_Test_REST_Controller_Testcas
$this->assertEquals( $parent->term_id, $data['parent'] );
}
public function test_update_item_remove_parent() {
wp_set_current_user( self::$administrator );
$old_parent_term = get_term_by( 'id', $this->factory->category->create(), 'category' );
$new_parent_id = 0;
$term = get_term_by(
'id',
$this->factory->category->create(
[
'parent' => $old_parent_term->term_id,
]
),
'category'
);
$this->assertEquals( $old_parent_term->term_id, $term->parent );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories/' . $term->term_id );
$request->set_param( 'parent', $new_parent_id );
$response = rest_get_server()->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( $new_parent_id, $data['parent'] );
}
public function test_update_item_invalid_parent() {
wp_set_current_user( self::$administrator );
$term = get_term_by( 'id', $this->factory->category->create(), 'category' );