我们在wordpress开发中, 在调取分类下的文章,我们通常是使用query_posts()函数,今天我们一起总结一下各种方法的优劣。
一、使用query_posts()函数
以下代码实际上使用query_posts()函数调取分类目录下的文章,showposts是调取的数量。
cat_ID );
?>
cat_name; ?>
在官方文档中,这样强调:“如果我们不得不用到query_posts(),必须确保每次使用query_posts()后同时执行wp_reset_query();”。这就是为什么在上面的代码中加上了wp_reset_query()的原因。
修改其中的数字10可以设定显示的篇数,可用于在单页面上显示全部分类文章。
二、使用get_posts()函数
只需通过get_posts来获取分类ID就可以输出分类下的文章,以及通过numberposts来控制文章显示的数量。
三、结合wp_list_categories()函数输出分类标题
四、自定义函数
1、我们自定义一个函数popularPosts()
function popularPosts($num) {
global $wpdb;
$posts = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , $num");
foreach ($posts as $post) {
setup_postdata($post);
$id = $post->ID;
$title = $post->post_title;
$count = $post->comment_count;
if ($count != 0) {
$popular .= '这里使用get_results()查询了数据库,相对速度快一点。
2、调用函数 popularPosts(10) 显示10篇文章。
div class="popular">
Most Popular Posts
WordPress后台中实现图片上传功能
[教学]在网页上加入HTML5 的Video Tag,直接播放MP4、OGG…等影片




