WordPress中have_posts()不返回私密文章?如何让分类页显示私密文章
解决WordPress分类页显示私密文章的问题
要让分类页显示私密文章,需修改WordPress的主查询规则,同时确保只有有权限的用户能查看这些内容,具体操作如下:
1. 添加查询修改钩子
在主题的functions.php文件中插入以下代码,让分类页的查询包含私密文章状态:
add_action('pre_get_posts', 'include_private_posts_in_categories'); function include_private_posts_in_categories($query) { // 仅对前台分类页的主查询生效 if (!is_admin() && $query->is_main_query() && is_category()) { // 验证当前用户是否有权限查看私密文章 if (current_user_can('read_private_posts')) { $query->set('post_status', array('publish', 'private')); } } }
2. (可选)标注私密文章
如果需要让用户直观区分私密文章,可修改category.php中的文章标题代码,添加私密标识:
<?php while (have_posts()) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php $title = get_the_title(); // 给私密文章添加标识 if (get_post_status() === 'private') { $title .= ' <span style="color:#dc3545;">[私密]</span>'; } echo '<a href="'.get_the_permalink().'"><h3>'.$title.'</h3></a>'; ?> </article> <?php endwhile; ?>
说明
- 只有拥有
read_private_posts权限的用户(默认是管理员、编辑、文章作者)能看到分类页里的私密文章,普通访客无法查看,保障内容安全。 - 修改
functions.php前建议备份文件,避免操作失误影响网站运行。
内容的提问来源于stack exchange,提问作者alancc
相关产品推荐
相关产品推荐

