如何在WordPress中仅显示当前用户发布的文章?
实现WordPress前端仅显示当前用户的文章网格
以下是几种直接有效的实现方案,覆盖列表查询和单页访问限制:
1. 用pre_get_posts钩子限制文章列表查询
这是最通用的方法,直接修改WordPress主查询,让前端文章列表只加载当前登录用户的内容。将代码添加到主题的functions.php文件或自定义插件中:
add_action( 'pre_get_posts', 'restrict_posts_to_current_user' ); function restrict_posts_to_current_user( $query ) { // 仅对前端主查询生效,排除后台操作 if ( ! is_admin() && $query->is_main_query() && is_user_logged_in() ) { // 设置查询仅返回当前用户发布的文章 $query->set( 'author', get_current_user_id() ); } }
适配自定义文章类型
如果你的客户项目是用自定义文章类型(比如client_project)创建的,修改代码针对性限制该类型:
add_action( 'pre_get_posts', 'restrict_custom_posts_to_current_user' ); function restrict_custom_posts_to_current_user( $query ) { if ( ! is_admin() && $query->is_main_query() && is_user_logged_in() ) { // 替换为你的自定义文章类型名称 $target_post_type = 'client_project'; if ( $query->get('post_type') === $target_post_type || is_post_type_archive($target_post_type) ) { $query->set( 'author', get_current_user_id() ); } } }
2. 限制单篇文章的直接访问
上面的方法只处理了列表页,用户仍可能通过直接输入URL访问他人的文章。添加以下代码防止这种情况:
add_action( 'template_redirect', 'block_unauthorized_post_access' ); function block_unauthorized_post_access() { if ( is_single() && is_user_logged_in() && ! is_admin() ) { $current_user = get_current_user_id(); $post_author = get_post_field( 'post_author', get_the_ID() ); // 若当前用户不是文章作者,跳转至404页面 if ( $current_user !== $post_author ) { wp_redirect( get_404_template() ); exit; } } }
注意事项
- 推荐将代码放在自定义插件中,避免主题更新导致代码丢失;
- 如果使用页面构建器制作文章网格,需确认其查询逻辑:若为自定义查询,需手动添加
'author' => get_current_user_id()参数; - 测试时切换不同用户账号,验证是否只能查看自己发布的内容。
内容的提问来源于stack exchange,提问作者Luis Carvalho
相关产品推荐
相关产品推荐

