WP_Query 常用参数速查

作者: admin 分类: wordpress主题制作教程 发布时间: 2026-11-06 18:30

参数太多,先分类

WP_Query 的参数有几十个,硬背肯定记不住。但它们其实分四类:查多少、查哪些、怎么排、查什么状态。按类记,就不会乱。

一、查多少

参数 作用 例子
posts_per_page 每页几条 5 / -1(全部)
offset 跳过前几条 3(跳过最新 3 篇)
paged 第几页 分页时用

posts_per_page => -1 要慎用:它会查出所有文章,文章多了会拖慢页面。

二、查哪些

参数 作用 例子
cat 按分类 ID 5 或 '5,-3'(排除 3)
category_name 按分类别名 'wordpress'
tag 按标签别名 'seo'
tag__in 按标签 ID 数组 array(1,2,3)
post__in 指定文章 ID array(10,20,30)
post__not_in 排除文章 ID array($post->ID)
s 搜索关键词 'wordpress'
author 按作者 ID 1

相关文章最常用的组合:tag__in + post__not_in(同标签,排除自己)。

三、怎么排

参数 作用 例子
orderby 按什么排 date / comment_count / rand / title
order 升序还是降序 DESC(默认)/ ASC
  • date:按发布时间(最常用);
  • comment_count:按评论数(做“热门文章”);
  • rand:随机(做“随机推荐”,但每次刷新都变,SEO 不友好);
  • modified:按修改时间。

四、查什么状态

参数 作用 说明
post_status 文章状态 默认 publish
post_type 文章类型 默认 post,可改 page
ignore_sticky_posts 忽略置顶 做列表时建议加 1

post_status 默认只查已发布。如果你在后台预览草稿,用 WP_Query 是查不到的,这是正常的。

一个完整例子:热门文章

$hot = new WP_Query( array(
    'posts_per_page'      => 8,
    'orderby'             => 'comment_count',
    'order'               => 'DESC',
    'ignore_sticky_posts' => 1,
    'post_status'         => 'publish',
) );

这段就是“按评论数排,取前 8 篇”。侧栏里放一份,挺实用。

一个完整例子:同标签相关文章

$tags = array();
foreach ( get_the_tags() as $t ) { $tags[] = $t->term_id; }

$related = new WP_Query( array(
    'tag__in'             => $tags,
    'post__not_in'        => array( get_the_ID() ),
    'posts_per_page'      => 6,
    'ignore_sticky_posts' => 1,
) );

小结

一句话记住:四类参数——查多少(posts_per_page/offset)、查哪些(cat/tag__in/post__not_in)、怎么排(orderby/order)、什么状态(post_status/ignore_sticky_posts)。

下次要用,按这四类去查,比死记参数名快得多。

下一篇讲一个更“正规”的入口:想改主查询,应该用 pre_get_posts,而不是 query_posts。

本系列导航

相关文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Powered by 草根站长笔记 © 2015-2026 草根站长笔记 Inc.版权所有,禁止转载