Posts, Post Types: Check if taxonomy is set for the `tax_input` parameter of `wp_insert_post()`.

This avoids a PHP notice when creating a post with multiple taxonomies both having a default term.

Props yakimun, szaqal21, hareesh-pillai, audrasjb.
Fixes #51320.

git-svn-id: https://develop.svn.wordpress.org/trunk@49328 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Sergey Biryukov 2020-10-27 16:40:35 +00:00
parent 986becfd4d
commit fce8f2bf4d
2 changed files with 28 additions and 6 deletions

View File

@ -4091,7 +4091,7 @@ function wp_insert_post( $postarr, $wp_error = false, $fire_after_hooks = true )
if ( ! empty( $tax_object->default_term ) ) {
// Filter out empty terms.
if ( isset( $postarr['tax_input'] ) && is_array( $postarr['tax_input'][ $taxonomy ] ) ) {
if ( isset( $postarr['tax_input'][ $taxonomy ] ) && is_array( $postarr['tax_input'][ $taxonomy ] ) ) {
$postarr['tax_input'][ $taxonomy ] = array_filter( $postarr['tax_input'][ $taxonomy ] );
}

View File

@ -1007,14 +1007,14 @@ class Tests_Taxonomy extends WP_UnitTestCase {
);
// Add post.
$post_id = wp_insert_post(
$post_id = self::factory()->post->create(
array(
'post_title' => 'Foo',
'post_type' => 'post',
)
);
// Test default category.
// Test default term.
$term = wp_get_post_terms( $post_id, $tax );
$this->assertSame( get_option( 'default_term_' . $tax ), $term[0]->term_id );
@ -1028,16 +1028,18 @@ class Tests_Taxonomy extends WP_UnitTestCase {
'taxonomies' => array( $tax ),
)
);
$post_id = wp_insert_post(
$post_id = self::factory()->post->create(
array(
'post_title' => 'Foo',
'post_type' => 'post-custom-tax',
)
);
$term = wp_get_post_terms( $post_id, $tax );
// Test default term.
$term = wp_get_post_terms( $post_id, $tax );
$this->assertSame( get_option( 'default_term_' . $tax ), $term[0]->term_id );
// wp_set_object_terms shouldn't assign default category.
// wp_set_object_terms() should not assign default term.
wp_set_object_terms( $post_id, array(), $tax );
$term = wp_get_post_terms( $post_id, $tax );
$this->assertSame( array(), $term );
@ -1046,6 +1048,26 @@ class Tests_Taxonomy extends WP_UnitTestCase {
$this->assertSame( get_option( 'default_term_' . $tax ), false );
}
/**
* @ticket 51320
*/
function test_default_term_for_post_in_multiple_taxonomies() {
$post_type = 'test_post_type';
$tax1 = 'test_tax1';
$tax2 = 'test_tax2';
register_post_type( $post_type, array( 'taxonomies' => array( $tax1, $tax2 ) ) );
register_taxonomy( $tax1, $post_type, array( 'default_term' => 'term_1' ) );
register_taxonomy( $tax2, $post_type, array( 'default_term' => 'term_2' ) );
$post_id = self::factory()->post->create( array( 'post_type' => $post_type ) );
$taxonomies = get_post_taxonomies( $post_id );
$this->assertContains( $tax1, $taxonomies );
$this->assertContains( $tax2, $taxonomies );
}
/**
* Ensure custom callbacks are used when registered.
*