wordpress wp_insert_post& wp_update_post

时间:2013-07-12 14:55:38

标签: wordpress

我想从wordpress网站的前端创建一个帖子。

当人们使用相同的post_title添加帖子时,我希望该帖子得到更新,而不是创建新帖子。

我有以下内容:

if (!get_page_by_title($post_title, 'OBJECT', 'post') ){
$my_post = array(
   'post_title'    => $post_title,
  'post_content'  => $post_content,
  'post_status'   => 'publish',
  'post_author'   => $post_author,
  'post_category' => $post_categories
);

wp_insert_post( $my_post );

}

else {

$page = get_page_by_title($post_title);
$page_id = $page->ID;

$my_post = array(

   'ID' =>  $page_id,
   'post_title'    => $post_title,
  'post_content'  => $post_content,
  'post_status'   => 'publish',
  'post_author'   => $post_author,
  'post_category' => $post_categories
);

wp_update_post( $my_post );

}

上述工作正常,直到帖子标题相同。它仍将在数据库中重复,甚至不会考虑“else”语句。

以上看起来没问题,或者我做错了什么?

2 个答案:

答案 0 :(得分:11)

如果对数组使用empty检查

,该怎么办?

请注意,即使帖子被删除,它也会获得数据库中的第一个帖子/页面项目。

$check_title=get_page_by_title($post_title, 'OBJECT', 'post');

//also var_dump($check_title) for testing only

if (empty($check_title) ){
$my_post = array(
   'post_title'    => $post_title,
  'post_content'  => $post_content,
  'post_status'   => 'publish',
  'post_author'   => $post_author,
  'post_category' => $post_categories
);

wp_insert_post( $my_post );

}

else {


$my_post = array(

   'ID' =>  $check_title->ID,
   'post_title'    => $post_title,
  'post_content'  => $post_content,
  'post_status'   => 'publish',
  'post_author'   => $post_author,
  'post_category' => $post_categories
);

wp_update_post( $my_post );

}

答案 1 :(得分:0)

对于“自定义帖子类型”,请将第一行更改为:

$check_title=get_page_by_title($post_title, 'OBJECT', 'my_custom_post_type');