WordPress如何为已有审核通过文章的作者自动将新投稿从pending转为approved
问题排查
你的代码存在以下几个核心错误:
- 钩子使用错误:
wp_insert_post是动作钩子(action),无法用来过滤修改待插入的文章数据,你需要改用wp_insert_post_data过滤器,同时你注册钩子时声明接受2个参数,但自定义函数只定义了1个入参,参数不匹配。 - 作者ID变量未定义:查询参数里的
$id没有赋值,你需要从传入的文章数据中获取当前文章的作者ID。 - 查询性能冗余:不需要查询该作者所有已通过文章,只要判断是否存在至少1条即可,
posts_per_page设为1就能满足需求,减少数据库查询压力。 - 没有排除更新场景:没有区分是新创建文章还是更新旧文章的请求,会导致旧文章更新时状态被意外修改。
修复后代码
add_filter('wp_insert_post_data', 'change_post_status_when_insert_post_data', 10, 2); function change_post_status_when_insert_post_data($data, $postarr) { // 仅处理post类型、且为新创建文章的场景 if($data['post_type'] == "post" && !isset($postarr['ID'])) { // 提取当前文章的作者ID $author_id = $data['post_author']; $posts_args = array( 'author' => $author_id, 'post_type' => 'post', 'post_status' => 'approved', 'posts_per_page' => 1, 'no_found_rows' => true, // 跳过分页统计,优化查询性能 ); $user_approved_posts = get_posts($posts_args); if(count($user_approved_posts) > 0) { $data['post_status'] = 'approved'; } else { $data['post_status'] = 'pending'; } } return $data; }
内容的提问来源于stack exchange,提问作者TrinhQuangTruong
相关产品推荐
相关产品推荐

