NOTES FROM EVERYDAY LIFE技术笔记
技术笔记

WP_Query类使用方法–调用指定作者的文章或页面

使用 WP_Query 的 author、author_name 与 author__in 参数查询指定作者的文章。

按作者查询文章,最直接的参数是 author,值为用户 ID。若按用户公开 slug 查询,则使用 author_name;它接收的是 user_nicename,不是显示名称。

$query = new WP_Query( array(
    'post_type'           => 'post',
    'post_status'         => 'publish',
    'author'              => 12,
    'posts_per_page'      => 10,
    'ignore_sticky_posts' => true,
) );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        the_title( '<h2>', '</h2>' );
    }
}
wp_reset_postdata();

多个作者使用 author__in,排除作者使用 author__not_in。来自 URL 或表单的 ID 先用 absint() 或 wp_parse_id_list() 清理。自定义循环结束后调用 wp_reset_postdata(),否则后面的模板标签可能继续读取自定义查询中的文章。

如果只是修改主查询,不要重新创建第二个循环;在 pre_get_posts 中确认 ! is_admin() 与 $query->is_main_query() 后设置作者参数,更省一次数据库查询。


参考资料

技术笔记
谢谢你,花时间读到这里。
回到文章列表