diff --git a/src/wp-includes/post.php b/src/wp-includes/post.php index d999c7bfeb..b434ae52e4 100644 --- a/src/wp-includes/post.php +++ b/src/wp-includes/post.php @@ -4142,6 +4142,8 @@ function wp_insert_post( $postarr, $wp_error = false, $fire_after_hooks = true ) if ( ! empty( $postarr['post_category'] ) ) { // Filter out empty terms. $post_category = array_filter( $postarr['post_category'] ); + } elseif ( $update && ! isset( $postarr['post_category'] ) ) { + $post_category = $post_before->post_category; } // Make sure we set a valid category. diff --git a/tests/phpunit/tests/post/wpInsertPost.php b/tests/phpunit/tests/post/wpInsertPost.php index 5a8ce8f2d9..a86d6560d1 100644 --- a/tests/phpunit/tests/post/wpInsertPost.php +++ b/tests/phpunit/tests/post/wpInsertPost.php @@ -876,6 +876,51 @@ class Tests_Post_wpInsertPost extends WP_UnitTestCase { $this->assertSame( $changeset_data, json_decode( get_post( $post_id )->post_content, true ) ); } + /** + * @ticket 19954 + */ + function test_updating_a_post_should_not_trash_categories() { + // Create a category and attach it to a new post. + $term_id = self::factory()->term->create( + array( + 'name' => 'Term', + 'taxonomy' => 'category', + ) + ); + + $post_id = self::factory()->post->create( + array( + 'post_type' => 'post', + 'post_title' => 'Post with categories', + 'post_status' => 'publish', + 'post_category' => array( $term_id ), + ) + ); + + // Validate that the term got assigned. + $assigned_terms = wp_get_object_terms( array( $post_id ), array( 'category' ), array() ); + $this->assertCount( 1, $assigned_terms ); + $this->assertEquals( $term_id, $assigned_terms[0]->term_id ); + + // Update the post with no changes. + $post = get_post( $post_id ); + wp_insert_post( $post ); + + // Validate the term is still assigned. + $assigned_terms = wp_get_object_terms( array( $post_id ), array( 'category' ), array() ); + $this->assertCount( 1, $assigned_terms ); + $this->assertEquals( $term_id, $assigned_terms[0]->term_id ); + + // Remove the term from the post. + $post->post_category = array(); + wp_insert_post( $post ); + $assigned_terms = wp_get_object_terms( array( $post_id ), array( 'category' ), array() ); + + // Validate that the post has had the default category assigned again. + $this->assertCount( 1, $assigned_terms ); + $this->assertEquals( get_option( 'default_category' ), $assigned_terms[0]->term_id ); + } + /** * @ticket 48113 */