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; ?>