WordPress 迴圈讀取文章資料的方法一般使用 query_posts(WordPress query_post 函式應用介紹) 這個函式。
但是使用 query_posts 這個函式有一些弊端:

  • 可能會干擾那些用到的 Loop(迴圈) 的外掛。
  • 可能使一些 WordPress 條件標籤失效。
  • 需要去處理重新設定,重新倒回和偏移等問題。

而 WP_Query 可以很好的解決這些問題,WP_Query 可以自定義 WordPress 的迴圈。

WP_Query 應用

例如我們要輸出最新的 5 篇文章,程式碼如下:

<?php
    $recentPosts = new WP_Query();
    $recentPosts->query('showposts=5');
?>

我們透過例項化 WP_Query 類,然後使用 query 函式來呼叫最新的 5 篇文章資料。 query() 函式中的變數使用與 query_posts() 的函式變數使用是一樣的
OK!我們現在透過讀取的資料來迴圈讀取最新的 5 篇文章資料

<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
   <!--迴圈體,讀取資料 -->
<?php endwhile; ?>

我們這裡用了 WP_Query 的兩個方法,分別是 have_posts 和 the_post 。你可以從這篇文章全域性變數和 WordPress 主迴圈瞭解更多關於這兩個函式。這樣我們就可以使用文章迴圈體的常用函式:文章連結-the_permalink(), 文章標題 the_title() 等。
完整程式碼

以下為讀取最新 5 篇文章的完整程式碼:

<h3> 最新文章</h3>
<ul>
<?php
    $recentPosts = new WP_Query();
    $recentPosts->query('showposts=5');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
    <li><a href="<?php%20the_permalink()%20?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

<h2>WP_Query 總結</h2>

使用 WP_Query 來讀取文章資料其實是跟 query_post() 函式差不多,不過他可以規避 query_post() 存在的不足,WP_Query 還是值得推薦使用的。

我們還可以用 WP_Query 來解決 WP-pagenavi 分頁無效的問題:

<?php $wp_query = new WP_Query(『cat=43&orderby=title&order=asc&posts_per_page=3&paged=』.$paged); ?>
<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
……

<?php endwhile; ?>