如何将内容插入我的分类中

时间:2012-04-04 作者:SANS780730

如何将内容插入我的分类法此代码是否正确?

   // Create post object
  $my_post = array(
 \'post_title\' => \'My post\',
 \'post_content\' => \'This is my post.\',
 \'post_status\' => \'publish\',
 \'post_author\' => 1,
  \'tax_input\' => array( \'taxonomy_name\' => array( \'Newpostlist\' ) ) , 
 \'post_category\' => array(8,39),

   );

      // Insert the post into the database
       wp_insert_post( $my_post );

2 个回复
SO网友:Boone Gorges

您正在使用tax_input 不正确。你不应该这么说taxonomy_name, 您应该输入自定义分类法的名称。看见https://codex.wordpress.org/Function_Reference/wp_insert_post. 所以,假设你的分类法叫做“忍者神龟”,你在帖子上贴上的标签是“多纳泰罗”和“米开朗基罗”:

// Create post object
$my_post = array(
    \'post_title\' => \'My post\',
    \'post_content\' => \'This is my post.\',
    \'post_status\' => \'publish\',
    \'post_author\' => 1,
    \'tax_input\' => array( \'ninja_turtles\' => array( \'donatello\', \'michelangelo\' ) ) , 
    \'post_category\' => array(8,39),
);

// Insert the post into the database
wp_insert_post( $my_post );
没有什么特别的原因(除了它让我觉得我有更细粒度的控制之外),我个人不喜欢使用tax_input 但要使用独立功能wp_set_post_terms() https://codex.wordpress.org/Function_Reference/wp_set_post_terms 创建帖子后:

// Create post object
$my_post = array(
    \'post_title\' => \'My post\',
    \'post_content\' => \'This is my post.\',
    \'post_status\' => \'publish\',
    \'post_author\' => 1,
    \'post_category\' => array(8,39),
);

// Insert the post into the database
$post_id = wp_insert_post( $my_post );

// If all was successful, add the terms
if ( $post_id ) {
    wp_set_post_terms( $post_id, array( \'donatello\', \'michelangelo\' ), \'ninja_turtles\' );
}

SO网友:Sam Margulies

这段代码似乎是正确的,但要找出答案,唯一的方法就是尝试一下。有关添加帖子的更多信息,请访问wp_insert_post() WordPress codex上的第页。

结束