WordPress wp_insert_post不插入标签


WordPress wp_insert_post not inserting tags

我正在尝试使用以下代码插入帖子:

$my_post = array(
                'post_type'    => "essays",
                'post_title'    => 'TEST 3',
                //'post_content'  => $content,
                'post_status'   => 'draft',
                'post_author'   => 1,
                //'post_category' => $cat,
                'tags_input'    => 'TQM,tag',
        );
$post_id = wp_insert_post($my_post);

除了标签之外,一切都可以正常工作,它不会插入任何标签。知道吗?

使用 wp_set_object_terms() 函数:

http://codex.wordpress.org/Function_Reference/wp_set_object_terms

wp_set_object_terms($post_id , $arrayoftags, $name_of_tag_taxonomy, false);

祝你好运

您的帖子类型是 essays 。默认情况下,自定义帖子类型不支持标签。您必须为它们添加tags分类法。

http://codex.wordpress.org/Taxonomies

http://codex.wordpress.org/Function_Reference/register_taxonomy

要插入带有标签和类别的帖子,请执行以下操作

$pid=wp_insert_post($new_post);
wp_set_post_terms( $pid, $arrayoftags);
wp_set_post_categories( $pid, $arrayofcategories );
所以帖子 ID $pid基本上你首先插入没有标签或类别的帖子,该函数返回帖子的 ID,然后您可以使用该 ID 插入标签和类别,

每个标签和类别都有各自的功能,如果您查看wp_insert_post的源代码,您会注意到该函数以不同的方式用于自定义帖子类型, 我没有深入研究它,因为我不想破解代码,因为使用内置函数有更好的解决方案

嗨,我在某处找到了这个答案,这可能会对您有所帮助

//first get the term (I used slug, but  you can aslo use 'name'), see: http://codex.wordpress.org/Function_Reference/get_term_by
$term = get_term_by( 'slug', 'your custom term slug', 'your custom taxonomy' );
//then get the term_id
$term_id = $term->term_id;
//Use 'tax_input' instead of 'post_category' and provide the term_id:
'tax_input' => array( 'your taxonomy' => $term_id )

希望有帮助。

标签和帖子类别应该作为一个数组输入,即使它只有一个。所以'tags_input' => 'TQM,tag'应该'tags_input' => array('TQM,tag')