desmeit
desmeit

Reputation: 660

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?

Upvotes: 8

Views: 16255

Answers (2)

rafa226
rafa226

Reputation: 546

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/

Upvotes: 2

Noman
Noman

Reputation: 4116

You would need to use:

1- get_term_by to get term obj
2- wp_set_object_terms to set custom taxonomy's term with post

$post_id = wp_insert_post($new_post);
$taxonomy = 'user_r_category';
$termObj  = get_term_by( 'id', 7, $taxonomy);
wp_set_object_terms($post_id, $termObj, $taxonomy);

Upvotes: 4

Related Questions