【问题标题】:Wordpress - Programmatically inserting posts with NEW categories?Wordpress - 以编程方式插入具有新类别的帖子?
【发布时间】:2011-01-29 00:34:03
【问题描述】:

我编写了一个脚本,它接受一些新闻的 XML 提要,并使用 wp_insert_post() 将每个新闻故事作为帖子插入 WordPress。

这些新闻故事中的每一个都有一个我想添加到 WordPress 的类别。

我的问题是,如何使用 wp_insert_post()(或任何其他函数)即时创建新类别并将帖子分配给该类别?

谢谢!

【问题讨论】:

  • 我不知道 WordPress 中有任何功能可以做到这一点。但是,您可以使用自定义调用将类别标题/ID 添加到表中。

标签: wordpress


【解决方案1】:

我最后通过编写如下代码进行了排序:

//Check if category already exists
$cat_ID = get_cat_ID( $category );

//If it doesn't exist create new category
if($cat_ID == 0) {
    $cat_name = array('cat_name' => $category);
    wp_insert_category($cat_name);
}

//Get ID of category again incase a new one has been created
$new_cat_ID = get_cat_ID($category);

// Create post object
$new_post = array(
    'post_title' => $headline,
    'post_content' => $body,
    'post_excerpt' => $excerpt,
    'post_date' => $date,
    'post_date_gmt' => $date,
    'post_status' => 'publish',
    'post_author' => 1,
    'post_category' => array($new_cat_ID)
);

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

【讨论】:

    【解决方案2】:

    试试这个:

    $my_cat = array('cat_name' => 'My Category', 'category_description' => 'A Cool Category', 'category_nicename' => 'category-slug', 'category_parent' => '');
    
    $my_cat_id = wp_insert_category($my_cat);
    
    $my_post = array(
       'post_title' => 'My post',
       'post_content' => 'This is my post.',
       'post_status' => 'publish',
       'post_author' => 1,
       'post_category' => array($my_cat_id)
    );
    
    wp_insert_post( $my_post );
    

    警告:未经测试。都被拿走了 来自wp_insert_post()wp_insert_category() 页面打开 法典。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-18
      • 2019-04-15
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 2014-06-19
      相关资源
      最近更新 更多