WordPress的主循环和WP_Query是主题开发中最重要的两个概念,它们负责从数据库获取内容并显示在页面上。
主循环 (The Loop)
主循环是WordPress用来显示文章的核心机制。它是一个PHP代码结构,用于遍历当前页面请求的文章集合并显示每篇文章的内容。基本的主循环结构如下:
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
// 显示文章内容
the_title('<h2>', '</h2>');
the_content();
endwhile;
else:
// 没有找到文章时的内容
echo '<p>没有找到任何文章</p>';
endif;
?>
主循环常用函数:
have_posts() - 检查是否还有文章需要显示
the_post() - 设置当前文章,准备显示
the_title() - 显示文章标题
the_content() - 显示文章内容
the_excerpt() - 显示文章摘要
the_permalink() - 显示文章链接
the_time() - 显示文章发布时间
WP_Query类
WP_Query是WordPress提供的一个强大的类,用于从数据库查询文章。主循环实际上是使用默认的WP_Query实例。基本WP_Query用法:
<?php
$custom_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 5,
'category_name' => 'news'
) );
if ( $custom_query->have_posts() ) {
while ( $custom_query->have_posts() ) {
$custom_query->the_post();
// 显示文章内容
the_title();
the_content();
}
wp_reset_postdata(); // 重置查询
} else {
// 没有找到文章
}
?>
常用查询参数:
post_type - 文章类型(post, page, 或自定义类型)
posts_per_page - 每页显示数量
category_name - 分类别名
tag - 标签
orderby - 排序字段(date, title, rand等)
order - 排序方式(ASC或DESC)
post_status - 文章状态(publish, draft等)
meta_key / meta_value - 自定义字段查询
主循环与WP_Query的关系
主循环使用全局的$wp_query对象,它是WP_Query的一个实例。当使用自定义WP_Query时,需要调用wp_reset_postdata()来恢复主查询。主循环是WordPress默认的内容显示机制,而WP_Query提供了更灵活的查询方式。
最佳实践
修改主查询使用pre_get_posts过滤器而不是直接修改$wp_query
自定义查询后总是使用wp_reset_postdata()
对于复杂查询,考虑使用WP_Query而不是直接SQL查询
使用wp_reset_query()当使用query_posts()后(但不推荐使用query_posts())
理解主循环和WP_Query是WordPress主题开发的基础,它们让你能够完全控制内容的显示方式。