From 0e0b10092c0f855619206982960ad857565d753d Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 30 Jan 2024 08:37:04 +0000 Subject: [PATCH] REST API: Support assigning terms when creating attachments. Props mukesh27, Dharm1025, Ankit K Gupta, swissspidy, dharm1025, tanjimtc71, timothyblynjacobs, spacedmonkey. Fixes #57897. git-svn-id: https://develop.svn.wordpress.org/trunk@57380 602fd350-edb4-49c9-b593-d223f7449a82 --- .../class-wp-rest-attachments-controller.php | 6 +++++ .../rest-api/rest-attachments-controller.php | 22 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php index c7da6d068b..d6bba7a924 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php @@ -186,6 +186,12 @@ class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller { return $fields_update; } + $terms_update = $this->handle_terms( $attachment_id, $request ); + + if ( is_wp_error( $terms_update ) ) { + return $terms_update; + } + $request->set_param( 'context', 'edit' ); /** diff --git a/tests/phpunit/tests/rest-api/rest-attachments-controller.php b/tests/phpunit/tests/rest-api/rest-attachments-controller.php index 0e721258ed..44c4027579 100644 --- a/tests/phpunit/tests/rest-api/rest-attachments-controller.php +++ b/tests/phpunit/tests/rest-api/rest-attachments-controller.php @@ -1045,6 +1045,28 @@ class WP_Test_REST_Attachments_Controller extends WP_Test_REST_Post_Type_Control $this->assertStringNotContainsString( ABSPATH, get_post_meta( $attachment['id'], '_wp_attached_file', true ) ); } + /** + * @ticket 57897 + * + * @requires function imagejpeg + */ + public function test_create_item_with_terms() { + wp_set_current_user( self::$author_id ); + register_taxonomy_for_object_type( 'category', 'attachment' ); + $category = wp_insert_term( 'Media Category', 'category' ); + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=canola.jpg' ); + + $request->set_body( file_get_contents( self::$test_file ) ); + $request->set_param( 'categories', array( $category['term_id'] ) ); + $response = rest_get_server()->dispatch( $request ); + $attachment = $response->get_data(); + + $term = wp_get_post_terms( $attachment['id'], 'category' ); + $this->assertSame( $category['term_id'], $term[0]->term_id ); + } + public function test_update_item() { wp_set_current_user( self::$editor_id ); $attachment_id = self::factory()->attachment->create_object(