我需要在创建新帖子时将帖子状态从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_posts
和count
来判断作者是否已经发表了一篇文章。
这个答案已经在wordpress5.8.1
上完全测试过了。