900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > wordpress获取分类下文章列表四种方法 – WP模板教程 – 前端

wordpress获取分类下文章列表四种方法 – WP模板教程 – 前端

时间:2018-08-20 12:01:20

相关推荐

wordpress获取分类下文章列表四种方法 – WP模板教程 – 前端

<?php$cats=get_categories();foreach($catsas$cat){query_posts(showposts=10&cat=.$cat->cat_ID);?><h3><?phpecho$cat->cat_name;?></h3><ulclass="sitemap-list"><?phpwhile(have_posts()){the_post();?><li><ahref="<?phpthe_permalink();?>"><?phpthe_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");?><?phpif($posts):?><ul><?phpforeach($postsas$post):setup_postdata($post);?><li><ahref=”<?phpthe_permalink()?>”rel=”bookmark”title=”<?phpthe_title();?>”><?phpthe_title();?></a></li><?phpendforeach;?></ul><?phpendif;?>

三、结合wp_list_categories函数输出分类标题

<h2><?phpwp_list_categories(include=11&title_li=&style=none);?></h2><!--//输出ID为11的分类的标题--><?phpechocategory_description(11);?><!--//输出ID为11的分类的描述--><?phpquery_posts(showposts=10&cat=11);?><!--//query_posts给TheLoop限定的条件是:显示12篇日志和分类ID为11--><?phpwhile(have_posts()):the_post();?><!--//TheLoop开始--><li><ahref="<?phpthe_permalink()?>"rel="bookmark"title="<?phpthe_title();?>"><?echowp_trim_words(get_the_title(),24);?></a><?phpthe_time(m/d);?></li><!--//用列表的方式输出带有链接的文章标题--><?phpendwhile;wp_reset_query();?><!--//TheLoop结束-->

四、自定义函数

1、大家自定义一个函数popularPosts

functionpopularPosts($num){global$wpdb;$posts=$wpdb->get_results("SELECTcomment_count,ID,post_titleFROM$wpdb->postsORDERBYcomment_countDESCLIMIT0,$num");foreach($postsas$post){setup_postdata($post);$id=$post->ID;$title=$post->post_title;$count=$post->comment_count;if($count!=0){$popular.=<li>;$popular.=<ahref=".get_permalink($id).\"title=".$title.\">.$title.</a>;$popular.=</li>;}}return$popular;}

这里使用get_results查询了数据库,相对速度快一点。

2、调用函数 popularPosts(10) 显示10篇文章。

<divclass="popular"><h2>MostPopularPosts</h2><ul><?phpechopopularPosts(10);?></ul></div>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。