wp_insert_post add meta_input

The question:

In the documentation of wp_insert_post there is a changelog on half of the page which says the following:

Since: WordPress 4.4.0 A ‘meta_input’ array can now be passed to
$postarr to add post meta data.

I’m using WordPress 4.4.2. I’ll try to add a new post by running the code as follows:

function handle_post($post) 
{
    wp_insert_post( array(
        'post_title'    => $post['title'],
        'post_type'     => 'werknemers',
        'meta_input'    => array(
            array(
                'key'   => 'name',
                'value' => $post['name']
            ),
            array(
                'key'   => 'city',
                'value' => $post['city']
            )
        )
    ) ); 
}

The post is added to the database, but without meta data.
I’ve found this stack post, but I can’t figure out how to implement the if statement.

I’m also interested in the way to add taxonomies (tax_input).

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

meta_input is just a single-dimension array as key => value:

'meta_input' => array(
    'name' => $post['name'],
    'city' => $post['city']
)

tax_input is slightly different, with tax as key and an array of values:

'tax_input' => array( 
    'taxonomy_name' => array( 
        'term', 
        'term2', 
        'term3' 
    ) 
)

Note that for tax_input to work, the user currently logged in when the code runs has to have the capability to manage that taxonomy, otherwise it will fail silently.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment