Make WordPress Core

Opened 10 years ago

Closed 10 years ago

Last modified 10 years ago

#33825 closed defect (bug) (invalid)

PHP warning on wp_insert_post, when tax_input variable is string

Reported by: ivanjankovic's profile ivan.jankovic Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.3
Component: Posts, Post Types Keywords:
Focuses: Cc:

Description

On creating new post:

                $new_post = array(
                    'post_title'    => 'test',
                    'post_content'  => '',
                    'post_status'   => 'publish',
                    'post_type'     => 'post',
                    'post_name'     => 'test',
                    'tax_input'     => 'test',
                );

you'll get warning:
PHP Warning: Invalid argument supplied for foreach() in /xyz/wp-includes/post.php on line 3471

Looks like tax_input argument expects an array, not string?

Change History (4)

#1 @swissspidy
10 years ago

Looks like tax_input argument expects an array, not string?

Yes, tax_input needs to be an array in the form of

array( 'my-taxonomy' => array( 'term-1', 'term-2' ) )

Otherwise the function doesn't know which taxonomy you mean. It has been documented now:

https://core.trac.wordpress.org/browser/trunk/src/wp-includes/post-functions.php#L2817

#3 @boonebgorges
10 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to invalid
  • Status changed from new to closed

Hi ivan.jankovic - Thanks for the ticket! Welcome to Trac.

As swissspidy notes, this is expected behavior. Unfortunately, this was not properly documented in the inline documentation for wp_insert_post() until [33922].

The docs at https://codex.wordpress.org/Function_Reference/wp_insert_post are actually correct, though they're somewhat confusing:

'tax_input'      => [ array( <taxonomy> => <array | string>, <taxonomy_other> => <array | string> ) ] 

This means that 'tax_input' must be an array (thus the square brackets), but that the value of a specific taxonomy key can optionally be a string. Eg:

'tax_input' => array( 'post_tag' => array( 3 ), 'category' => array( 5, 7 ) )
// or
'tax_input' => array( 'post_tag' => '3', 'category' => '5,7' )

#4 @ivan.jankovic
10 years ago

Thanks for explanation!

Note: See TracTickets for help on using tickets.