query_posts() 是一個 WordPress 函數,用于修改主循環中的查詢參數。它允許你根據自定義參數篩選文章,而不是使用默認的所有文章查詢。
以下是一個使用 query_posts() 的示例,該示例在自定義循環中顯示最近的 5 篇文章:
<?php
// 使用 query_posts() 自定義查詢參數
query_posts(array(
'posts_per_page' => 5, // 顯示 5 篇文章
'orderby' => 'date', // 按日期排序
'order' => 'DESC' // 降序排列,最近的文章在前
));
// 開始循環
if (have_posts()) : while (have_posts()) : 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_query();
?>
在這個示例中,我們使用 query_posts() 函數來自定義查詢參數。我們設置 posts_per_page 為 5,以便只顯示最近的 5 篇文章。我們還設置了 orderby 和 order 參數,以按日期降序排列文章。
在自定義循環結束后,我們使用 wp_reset_query() 函數重置查詢,以便在后續的循環中使用默認查詢參數。
請注意,盡管 query_posts() 函數可以實現自定義查詢,但它并不推薦使用,因為它會改變全局查詢,可能導致一些不可預見的問題。在大多數情況下,建議使用 pre_get_posts 鉤子或 WP_Query 類來實現自定義查詢。
另外一種用法:
<?php global $query_string; // 必需
$posts = query_posts($query_string.'&posts_per_page=3&cat=-6,-9&order=ASC'); ?>
<?php // 循環內容?>
<?php wp_reset_query(); // 重置 query ?>
3,為顯示數量
-6,-9為排除分類,如果是指定分類比如,指定分類ID為8的分類,就寫成cat=8即可。