Wordpress如何将帖子状态从待定更改为已批准



我需要在创建新帖子时将帖子状态从pending更改为approved,如果作者之前有过批准的帖子

我有一个这样的函数,但是代码根本不起作用。

请帮助:

add_filter('wp_insert_post', 'change_post_status_when_insert_post_data',10,2);
function change_post_status_when_insert_post_data($data) {
if($data['post_type'] == "post") {
$posts_args = array(
'author__in' => $id,
'post_type' => 'post',
'post_status' => 'approved',
'posts_per_page'  => -1,
);
$user_posts = get_posts($posts_args);
$count = count($user_posts);
if($count > 0) {
$data['post_status'] = 'approved';
} else {
$data['post_status'] = 'pending';
}
}
return $data;
}

代码根本不起作用

因为
  • wp_insert_post是动作钩子而不是过滤器钩子。因此,使用add_filter是不正确的。
  • 您要求wp_insert_post给您两个参数,但是您在回调函数中使用了一个。
  • $data是后object,它不是array。你不能像$data['post_type']那样使用它。
  • 'post_status' => 'approved'不存在。查看有效的帖子状态列表Docs
  • 您要查找的是publish而不是approved

下面的代码放在主题的functions.php文件中。

add_action('wp_insert_post', 'change_post_status_when_insert_post_data', 999, 2);
function change_post_status_when_insert_post_data($post_id, $post)
{
$posts_args = array(
'posts_per_page'  => -1,
'author'          => $post->post_author,
'post_status'     => 'publish',
);
$user_posts = new WP_Query($posts_args);
$post_status = (('post' == $post->post_type) && ($user_posts->found_posts) && ('publish' != $post->post_status) && ('trash' != $post->post_status)) ? 'publish' : 'pending';
if ('publish' == $post_status) {
wp_update_post(array(
'ID'            =>  $post_id,
'post_status'   =>  $post_status
));
}
}

我用来自动发布文章的条件:

  • post_type应该是'post'
  • 作者必须已经发表过至少一篇文章。
  • post_status不应该是publish
  • post_status也不应该是trash

值得一提的是,我使用了WP_Query及其属性found_posts,而不是使用get_postscount来判断作者是否已经发表了一篇文章。


这个答案已经在wordpress5.8.1上完全测试过了。

最新更新