为了添加现有术语或新术语,您需要使用wp_set_post_terms
通过检查term_exists
和使用wp_insert_term
如果没有。
类似这样:
$author_id = 1;
$slug = \'wordpress-post-created-with-code\';
$title = \'WordPress post created whith code\';
$content = \'This is the content of the post that we are creating right now with code.
More text: I motsetning til hva mange tror, er ikke Lorem Ipsum bare tilfeldig tekst.\';
$post_id = wp_insert_post(
array(
\'comment_status\' => \'closed\',
\'post_author\' => $author_id,
\'post_name\' => $slug,
\'post_title\' => $title,
\'post_content\' => $content,
\'post_status\' => \'publish\',
\'post_type\' => \'post\'
)
);
$taxonomy = \'<CUSTOM_TAXONOMY_SLUG>\';
if (term_exists(\'samsung\', $taxonomy)) {
$terms = array(\'samsung\');
wp_set_post_terms( $post_id, $terms, $taxonomy, true);
} else {
$term = \'samsung\';
$inserted_term = wp_insert_term( $term, $taxonomy);
if(!is_wp_error($inserted_term)) {
wp_set_post_terms( $post_id, $term, $taxonomy, true);
}
}