如何使用wp_插入_POST和POST_CATEGORY创建类别

时间:2019-07-07 作者:juan

我正在尝试用php及其wordpress函数创建一篇帖子。

我正在使用wp\\u insert\\u post(),但我无法为帖子指定自定义类别类型的文本,也无法创建它

我有以下代码:

require_once \'wp-load.php\';
// This is test snippet for learning purposes.
// Creates a WordPress Post with code.
$post_id = -1;
// Set the Author, Slug, title and content of the new post

$category=get_cat_ID( \'Samsung\' );
$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_category\'     =>  array($category),
        \'post_author\'       =>  $author_id,
        \'post_name\'         =>  $slug,
        \'post_title\'        =>  $title,
        \'post_content\'      =>  $content,
        \'post_status\'       =>  \'publish\',
        \'post_type\'         =>  \'post\'


    )


);
如您所见,我无法指定类别“Samsung”,如果没有类别,请创建itAny idea如何操作?非常感谢。

1 个回复
SO网友:Faham Shaikh

为了添加现有术语或新术语,您需要使用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);
    }
}

相关推荐

WP-CLI can't list posts

我有一个WordPress多站点(在防火墙后面)。我在很多方面都使用WP-CLI。但出于某种原因wp post list 不起作用。wp post get 作品但是wp post list 始终产生相同的输出,如下所示:正如您所看到的,这是一个没有数据的表。是否有人有调试此问题的提示?根据要求,我重新格式化了命令(没有任何区别),并添加了--debug。有很多输出!已添加post_type=page: