具有自定义分类法的 wp_insert_post

des*_*eit 6 php wordpress

我使用以下代码注册了自定义分类法:

register_taxonomy( 'user_r_category', array( 'user_r' ), $args );
Run Code Online (Sandbox Code Playgroud)

现在,我尝试将帖子插入到类别 ID 7 和 post_type 'user_r' 内的 'user_r_c​​ategory' 分类法:

$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);
Run Code Online (Sandbox Code Playgroud)

该帖子已创建,但不属于类别 7。这怎么行?

Nom*_*man 3

您需要使用:

1- get_term_by 获取术语 obj
2- wp_set_object_terms用 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);
Run Code Online (Sandbox Code Playgroud)