WordPress使用WP_Query查询文章方法

WordPress提供了多种方法查询文章,WP_Query是最灵活的查询文章方法,下面是使用方法介绍。

$args = array(
    'post_type'      => 'post',    // 文章类型(默认post)
    'posts_per_page' => 5,         // 显示数量
    'orderby'        => 'date',    // 按日期排序
    'order'          => 'DESC'     // 降序排列
);
$query = new WP_Query($args);
while ($query->have_posts()) : $query->the_post();
    the_title();  // 输出标题
    the_excerpt(); // 输出摘要
endwhile;
wp_reset_postdata(); // 重置查询

上面是WP_Query的基础用法,当然它还有其他参数,以下是 WP_Query 的常用参数分类整理:

一、基础查询参数

p - 指定文章/页面ID

post__in - 多篇文章ID数组

post__not_in - 排除指定ID的文章

post_type - 查询内容类型(默认'post')

二、作者相关

author - 作者ID(可逗号分隔多个)

author_name - 作者用户名

author__in - 包含的作者ID数组

author__not_in - 排除的作者ID数组

三、分类相关

cat - 分类ID(可逗号分隔)

category_name - 分类别名

category__in - 包含的分类ID数组

category__and - 同时属于多个分类

四、标签相关

tag - 标签别名

tag_id - 标签ID

tag__and - 同时包含多个标签

tag__not_in - 排除的标签ID数组

五、分页参数

posts_per_page - 每页显示数量

paged - 当前页码

offset - 查询偏移量

nopaging - 是否禁用分页(true/false)

六、排序参数

order - 排序方向(ASC/DESC)

orderby - 排序字段(date/title/rand等)

七、缓存参数

cache_results - 是否缓存查询结果

post_term_cache - 是否缓存term数据

update_post_meta_cache - 是否缓存meta数据

八、其他重要参数

post_status - 文章状态(publish/draft等)

meta_key/meta_value - 自定义字段查询

year/monthnum - 按日期筛选