WordPress中如何获取特定作者发布的所有页面(非文章)?
获取WordPress特定作者发布的所有页面(非文章)的PHP代码
你可以通过WordPress内置的WP_Query类实现这个需求,它能精准筛选指定作者发布的页面内容。以下是完整代码示例:
// 替换为目标作者的ID $target_author_id = 123; // 构建查询参数 $args = array( 'post_type' => 'page', // 指定查询类型为页面 'post_status' => 'publish', // 仅查询已发布的页面 'author' => $target_author_id, // 目标作者ID 'posts_per_page' => -1, // 获取所有符合条件的页面,不限制数量 'orderby' => 'date', // 按发布日期排序 'order' => 'DESC' // 降序排列,最新页面在前 ); // 执行查询 $author_pages = new WP_Query($args); // 处理查询结果 if ($author_pages->have_posts()) { while ($author_pages->have_posts()) { $author_pages->the_post(); ?> <div class="author-page-item"> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <p>发布时间:<?php the_date(); ?></p> <p><?php the_excerpt(); ?></p> </div> <?php } // 重置查询,避免影响后续全局数据 wp_reset_postdata(); } else { echo '该作者未发布任何页面。'; }
关键参数说明:
post_type => 'page':明确查询页面类型,区别于默认的文章postauthor:填写目标作者ID,可在WordPress后台用户列表中查看对应IDposts_per_page => -1:返回所有符合条件的页面,若需限制数量,改为具体数字即可post_status => 'publish':仅筛选已发布页面,如需包含草稿等状态,可改为'any'或指定状态数组
注意事项:
- 确保代码在WordPress环境中运行(如主题模板文件、自定义插件内),不要直接在外部PHP文件执行
- 执行完
WP_Query后必须调用wp_reset_postdata(),防止破坏后续全局查询环境 - 如需更复杂筛选(如排除特定页面、按自定义字段排序),可在
$args中添加对应参数
内容的提问来源于stack exchange,提问作者Homaira S
相关产品推荐
相关产品推荐

