wordpress获取分类下文章列表四种方法
导读:一、使用query_posts( 函数以下代码实际上使用query_posts( 函数调取分类目录下的文章,showposts是调取的数量。<?php $cats = get_categories( ; foreach (...
一、使用query_posts()函数
以下代码实际上使用query_posts()函数调取分类目录下的文章,showposts是调取的数量。
?php $cats = get_categories();
foreach ( $cats as $cat ) {
query_posts( 'showposts=10&
cat=' . $cat->
cat_ID );
?>
h3>
?php echo $cat->
cat_name;
?>
/h3>
ul class="sitemap-list">
?php while ( have_posts() ) {
the_post();
?>
li>
a href="?php the_permalink();
?>
">
?php the_title();
?>
/a>
/li>
?php }
wp_reset_query();
?>
/ul>
?php }
?>
在官方文档中,这样强调:“如果我们不得不用到query_posts(),必须确保每次使用query_posts()后同时执行wp_reset_query(); ”。这就是为什么在上面的代码中加上了wp_reset_query()的原因。
修改其中的数字10可以设定显示的篇数,可用于在单页面上显示全部分类文章。
二、使用get_posts()函数
只需通过get_posts来获取分类ID就可以输出分类下的文章,以及通过numberposts来控制文章显示的数量。
?php $posts = get_posts( "category=4&
numberposts=10" );
?>
?php if( $posts ) : ?>
ul>
?php foreach( $posts as $post ) : setup_postdata( $post );
?>
li>
a href=”?php the_permalink() ?>
” rel=”bookmark” title=”?php the_title();
?>
”>
?php the_title();
?>
/a>
/li>
?php endforeach;
?>
/ul>
?php endif;
?>
三、结合wp_list_categories()函数输出分类标题
h2>
?php wp_list_categories('include=11&
title_li=&
style=none');
?>
/h2>
!--//输出 ID 为11的分类的标题 -->
?php echo category_description(11);
?>
!--//输出 ID 为11的分类的描述 -->
?php query_posts('showposts=10&
cat=11');
?>
!-- //query_posts 给 The Loop 限定的条件是:显示12篇日志和分类 ID 为11 -->
?php while (have_posts()) : the_post();
?>
!--//The Loop 开始 -->
li>
a href="?php the_permalink() ?>
" rel="bookmark" title="?php the_title();
?>
">
? echo wp_trim_words( get_the_title(),24 );
?>
/a>
?php the_time('m/d');
?>
/li>
!-- //用列表的方式输出带有链接的文章标题-->
?php endwhile;
wp_reset_query();
?>
!--//The Loop 结束 -->
四、自定义函数
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 .= 'li>
';
$popular .= 'a href="' . get_permalink($id) . '" title="' . $title . '">
' . $title . '/a>
';
$popular .= '/li>
';
}
}
return $popular;
}
这里使用get_results()查询了数据库,相对速度快一点。
2、调用函数 popularPosts(10) 显示10篇文章。
div class="popular">
h2>
Most Popular Posts/h2>
ul>
?php echo popularPosts(10);
?>
/ul>
/div>
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: wordpress获取分类下文章列表四种方法
本文地址: https://pptw.com/jishu/40297.html
