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