Posts, Post Types: Prevent categories from being overwritten when updating a post using wp_insert_post().

This prevents existing category relationships being overridden with the default category when none is provided in the post data.

Props markoheijnen, leewillis77, desrosj

Fixes #19954


git-svn-id: https://develop.svn.wordpress.org/trunk@53883 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
John Blackbourn 2022-08-11 19:58:21 +00:00
parent 7bb8dc6269
commit 40c19e45bf
2 changed files with 47 additions and 0 deletions

View File

@ -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.

View File

@ -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
*/