WordPress wp_update_post()
功能出现错误,提示“无效的帖子ID”。这是我的代码:
$current_item = 273;
$my_post = array(
'ID' => $current_item,
'post_title' => 'This is the post title.',
'post_content' => 'This is the updated content.',
);
$post_id = wp_update_post( $my_post, true );
if (is_wp_error($post_id)) {
$errors = $post_id->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢 。
小智 5
使用'import_id'
,而不是'ID'
。
如果您指定的ID处没有帖子,wp_update_post()
则不会创建新帖子-它会返回错误。为了指定新帖子的ID,请使用'import_id' => $current_item
。
但是请注意,如果有一个具有该ID的帖子,import_id
将导致一个新帖子而不是更新。因此,如果您想使用该ID撰写新帖子或更新该ID上的帖子,则需要输入一条if
语句来选择密钥:
$newPostKey = (get_post_status($current_item)) ? 'ID' : 'import_id';
// If there's a post with an ID of $current_item, we'll use 'ID'.
// Otherwise, use 'import_id'.
Run Code Online (Sandbox Code Playgroud)
这是您闪亮的新代码。
$current_item = 273;
$newPostKey = (get_post_status($current_item)) ? 'ID' : 'import_id';
$my_post = array(
$newPostKey => $current_item,
'post_title' => 'This is the post title.',
'post_content' => 'This is the updated content.',
);
$post_id = wp_update_post( $my_post, true );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
771 次 |
最近记录: |