WP_Query 是 WordPress 中用于執行自定義查詢的類。它允許你根據自定義參數篩選文章,而不是使用默認的所有文章查詢。以下是一個使用 WP_Query 的示例,該示例在自定義循環中顯示最近的 5 篇文章:
<?php
// 使用 WP_Query 自定義查詢參數
$custom_query = new WP_Query(array(
'posts_per_page' => 5, // 顯示 5 篇文章
'orderby' => 'date', // 按日期排序
'order' => 'DESC' // 降序排列,最近的文章在前
));
// 開始循環
if ($custom_query->have_posts()) : while ($custom_query->have_posts()) : $custom_query->the_post(); ?>
<div class="post">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
<p>Posted on <?php the_time('F jS, Y'); ?> by <?php the_author(); ?></p>
</div>
<?php endwhile; else: ?>
<p>Sorry, no posts to display.</p>
<?php endif; ?>
// 重置查詢
wp_reset_postdata();
?>
在這個示例中,我們使用 WP_Query 類來自定義查詢參數。我們設置 posts_per_page 為 5,以便只顯示最近的 5 篇文章。我們還設置了 orderby 和 order 參數,以按日期降序排列文章。
在自定義循環結束后,我們使用 wp_reset_postdata() 函數重置查詢數據,以便在后續的循環中使用默認查詢參數。
與 query_posts() 不同,WP_Query 不會改變全局查詢,因此它是執行自定義查詢的推薦方法。如果你需要按分類篩選文章,可以在 WP_Query 參數中添加 cat 參數,就像在 query_posts() 示例中一樣。
為了想完全控制文章循環的數量,WP_Query 可以勝任這一任務,當我嘗試去修改默認的循環方式時,它看起來和query_posts非常相似。例如,使用WP_Query排除一些指定的category:
<?php $custom_query = new WP_Query('cat=-9'); // 排除 category 9
while($custom_query->have_posts()) : $custom_query->the_post(); ?>
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php the_content(); ?>
</div>
<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>
它接收了與query_posts相同的參數,包括排除或者包括指定categories以及修改顯示文章數量上它們基本上時一致的。但是你再看一下下面這幾段代碼你就會發現在使用自定義循環方面 WP_Query 會方便許多而且也非常容易修改參數。
$custom_query = new WP_Query('cat=-7,-8,-9'); // 排除指定 categories
$custom_query = new WP_Query('posts_per_page=3'); // 限制文章顯示數量
$custom_query = new WP_Query('order=ASC'); // 按照正序排序
正如我們所想的那樣,WP_Query 可以使用與query_posts 和get_posts相同的組合語法進行循環調用。
$custom_query = new WP_Query('posts_per_page=3&cat=-6,-9&order=ASC');
需要注意的是,無論在什么情況下只要你使用了WP_Query循環,那么我們就不再需要$query_string這個變量了,除了使用WP_Query 自定義默認循環外,我們也可以使用它來自定義更加多樣的循環,以下是代碼示例:
<?php // 循環1
$first_query = new WP_Query('cat=-1');
while($first_query->have_posts()) : $first_query->the_post();
...
endwhile;
wp_reset_postdata();
// 循環2
$second_query = new WP_Query('cat=-2');
while($second_query->have_posts()) : $second_query->the_post();
...
endwhile;
wp_reset_postdata();
// 循環 3
$third_query = new WP_Query('cat=-3');
while($third_query->have_posts()) : $third_query->the_post();
...
endwhile;
wp_reset_postdata();
?>
以上每一種循環方式都可以使用到你主題的任何地方,無需為它們進行排序,例如第一個循環可以放在側邊欄的位置,第二個放在頁腳的位置等等。每一種循環都很容易使用,你可以輸入一些有效的參數對其進行修改。
在什么樣的情況下可以使用?
WP_Query 可以用在多樣的自定義循環中,通過設置一些額外的功能,你可以創建任意數量的多個循環然后自定義每一種循環的輸出方式。
盡管如此,我們也并不需要每一次都派它上場,有些簡單循環你可以用默認循環和query_posts()循環就足夠了。