WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to use WP-CLI to create some new posts with custom taxonomy terms assigned. The challenge is that wp_insert_post's tax_input argument only accepts arrays, which I would have to specify on the command line. According to the codex, here is the format required:

$post = array(
    'tax_input' => [ array( 'taxonomy_name' => array( 'term', 'term2', 'term3' ) ) ] // support for custom taxonomies

But I need something like this:

wp post create --post_type=lecture --post_title='Test Post #1' --tax-input=[BIG FAT ARRAY]

So my idea was to write a PHP script that executes the WP-CLI command with the array serialized:

$post_title = "Test Post #1";
$tax_items = array( 9,11,17 );
$tax_input = array( 'course' => $tax_items );

$tax_escaped = escapeshellarg(serialize($tax_input));

$exec_string = 'wp post create --post_type=lecture --post_status=publish --post_title="%1$s" --tax_input=%2$s --porcelain';
$exec_command = sprintf($exec_string, $post_title, $tax_escaped );
$post_id = shell_exec($exec_command);

//wp post create --post_type=lecture --post_status=publish --post_title="Test Post #1" --tax_input='a:1:{s:5:"class";a:3:{i:0;i:9;i:1;i:11;i:2;i:17;}}' --porcelain

wp_set_object_terms( $post_id, $tax_items,'course');

Alas, this doesn't work. It creates the new post alright, but it fails to assign the 'course' taxonomy categories I want. Any help would be appreciated.

I know that this overall strategy works, because I succeeded in creating and taxonomizing my posts using wp_insert_posts. So this exercise is for educational purposes and future reference.

share|improve this question

This is probably impossible since WP-CLI pass the arguments directly to wp_insert_posts. I'm automating this with wp eval. For example:

wp eval 'wp_set_object_terms(12 , array(1, 2, 3), "course");'

The post id can be obtained when you create the post with --porcelain:

wp post create ... --porcelain

Or by normal query with post title:

wp eval 'wp_set_object_terms(get_page_by_title("Test Post #1", OBJECT, "lecture")->ID, array(1, 2, 3), "course");'
share|improve this answer

Normally you'd pass an array to a script on the command line using the following

# Our array is named "foo"
php yourscript.php foo[]=bar&foo[]=baz&foo[some_key]=some_value
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.