'wp_insert_post with custom taxonomy

I registered a custom taxonomy with this code:

register_taxonomy( 'user_r_category', array( 'user_r' ), $args );

Now I try to insert a post to 'user_r_category' taxonomy within the category ID 7 and the post_type 'user_r':

$new_post = array(
          //'ID' => '',
          'post_author' => $current_user->ID, 
          //'post_category' => array(7),
          'post_type'   => 'user_r',
          'post_content' => $r_textarea, 
          'post_title' => $r_title,
          'tax_input'    => array(
                            'user_r_category' => array( 7 )
                        ),
          'post_status' => 'publish'
        );

    $post_id = wp_insert_post($new_post);

The post was created, but not with the category 7. How could this work?



Solution 1:[1]

You can do it directly when inserting your post, with tax_input parameter :

$post = array(
    'post_title'    => $my_sanitized_title,
    'post_content'  => $my_sanitized_text,
    'post_status'   => 'publish',
    'post_type'     => 'post',
    'tax_input'    => array(
        'hierarchical_tax' => array($my_hierarchical_tax_id)
    ),
);
$post_id = wp_insert_post($post);

This is an array. See the doc for detailed parameters : https://developer.wordpress.org/reference/functions/wp_insert_post/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rafa226