get_posts() 是 WordPress 中用于獲取文章數據的函數。它允許你根據自定義參數篩選文章,而不是使用默認的所有文章查詢。以下是一個使用 get_posts() 的示例,該示例在自定義循環中顯示最近的 5 篇文章:

<?php
// 使用 get_posts() 自定義查詢參數
$custom_posts = get_posts(array(
    'posts_per_page' => 5, // 顯示 5 篇文章
    'orderby' => 'date',    // 按日期排序
    'order' => 'DESC'       // 降序排列,最近的文章在前
));
// 開始循環
if (!empty($custom_posts)) : foreach ($custom_posts as $post) : setup_postdata($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 endforeach; else: ?>
    <p>Sorry, no posts to display.</p>
<?php endif; ?>
// 重置查詢數據
wp_reset_postdata();
?>

在這個示例中,我們使用 get_posts() 函數來自定義查詢參數。我們設置 posts_per_page 為 5,以便只顯示最近的 5 篇文章。我們還設置了 orderby 和 order 參數,以按日期降序排列文章。

在自定義循環結束后,我們使用 wp_reset_postdata() 函數重置查詢數據,以便在后續的循環中使用默認查詢參數。

與 query_posts() 和 WP_Query 不同,get_posts() 不會改變全局查詢。它只是返回一個包含文章數據的數組,因此它是執行自定義查詢的另一種推薦方法。如果你需要按分類篩選文章,可以在 get_posts() 參數中添加 cat 參數,就像在 query_posts() 示例中一樣。

使用get_posts() 可以在你的主題中很方便的創建多樣化的循環,使用這種方法也是比較安全可靠的,你可以在任何地方快速的遍歷出文章,你可以嘗試使用 get_posts 。假如你想遍歷出最新發布的十篇文章,或者隨機發表的文章。使用get_posts將變得非常容易,下面是一些簡單的例子:

<?php global $post; // 必需
$args = array('category' => -9); // 排除 category 9
$custom_posts = get_posts($args);
foreach($custom_posts as $post) : setup_postdata($post);
...
endforeach;
?>

值得注意的是,無論什么情況下, get_posts是需要一個數組接收參數的,以下是使用數組的組合方式。

$args = array('numberposts'=>3, 'category'=>-6,-9, 'order'=>'ASC');