我想从我的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 );
}
Run Code Online (Sandbox Code Playgroud)
上述工作正常,直到帖子标题相同.它仍将在数据库中复制,甚至不会考虑"else"语句.
以上看起来不错,或者我做错了什么?
M K*_*aid 13
如果使用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 );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10375 次 |
| 最近记录: |