如何让自定义文章类型的待审核文章仅对其作者开放预览?
解决自定义文章类型待审核状态下作者预览问题
这个问题在WordPress里挺常见——默认情况下,待审核(pending)的文章只有管理员能查看,哪怕是文章作者自己也不行。不过我们可以通过几个关键的钩子来搞定这个需求,让作者只能预览自己创建的待审核deals文章,其他人还是看不到。
下面是具体的代码实现,你可以把这些代码添加到主题的functions.php文件里,或者创建一个简单的自定义插件来放置:
完整解决方案:查询调整 + 权限校验 + 拦截兜底
1. 让作者能查询到自己的待审核文章
首先用pre_get_posts钩子修改前台的主查询,让登录的作者能获取到自己的待审核deals文章:
add_action('pre_get_posts', 'allow_author_view_pending_deals'); function allow_author_view_pending_deals($query) { // 只处理前台的单个文章查询,且目标是deals类型 if (!is_admin() && $query->is_main_query() && $query->is_single() && $query->get('post_type') === 'deals') { $current_user = wp_get_current_user(); // 如果用户已登录且不是管理员 if ($current_user->ID && !current_user_can('manage_options')) { // 允许查询已发布和待审核的文章 $query->set('post_status', array('publish', 'pending')); // 只返回当前用户作为作者的文章 $query->set('author', $current_user->ID); } } }
2. 赋予作者查看自己待审核文章的权限
光修改查询还不够,WordPress的权限系统可能还是会拦截访问,所以用user_has_cap钩子调整权限规则:
add_filter('user_has_cap', 'author_can_view_own_pending_deals', 10, 3); function author_can_view_own_pending_deals($allcaps, $cap, $args) { // 检查是否是请求查看文章的权限,且传入了文章ID if ($cap[0] === 'read_post' && isset($args[2])) { $post_id = $args[2]; $post = get_post($post_id); // 如果文章是deals类型、状态为待审核,且当前用户是文章作者 if ($post && $post->post_type === 'deals' && $post->post_status === 'pending' && get_current_user_id() === $post->post_author) { // 赋予该用户查看权限 $allcaps['read_post'] = true; } } return $allcaps; }
3. 最后一道防线:拦截未授权访问
为了更稳妥,在template_redirect钩子里做最后的校验,防止漏网之鱼:
add_action('template_redirect', 'block_unauthorized_pending_deals'); function block_unauthorized_pending_deals() { global $post; // 只处理前台的deals文章,且状态为待审核 if (!is_admin() && $post && $post->post_type === 'deals' && $post->post_status === 'pending') { $current_user = wp_get_current_user(); // 如果用户不是管理员,也不是文章作者,直接跳转到404页面 if (!current_user_can('manage_options') && $current_user->ID !== $post->post_author) { wp_redirect(get_404_template()); exit; } } }
测试方法
- 用作者账号登录,创建一篇
deals文章并设置为待审核状态 - 访问该文章的预览链接(比如你提供的
http://localhost/project/?post_type=deals&p=3305),确认能正常查看 - 用其他作者账号或者未登录状态访问该链接,应该会跳转到404页面,无法查看
这样就精准实现了仅对作者开放自己创建的待审核deals文章的预览功能啦!
内容的提问来源于stack exchange,提问作者Pukhraj Suthar
相关产品推荐
相关产品推荐

