> WordPress中文手册 > wordpress WP_Query类的使用

WP_Query介绍

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 the_permalink() ?>" 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; ?>