wordpress在首页输出所有分类及文章
在站点的首页输出文章的所有分类以及分类下的文章,这通常都是CMS系统中不可缺少的,哪么在 wordpress 中如何将所有的分类及文章循环读取出来呢。
实例的代码如下:
<?php
$categories = get_categories();// 得到所有分类列表
foreach ($categories as $cat) {// 循环所有分类
$catid = $cat->cat_ID;// 得到分类ID
// 得到分类下10篇最新文章
query_posts("showposts=10&cat=".$catid.""); ?>
<div class="news">
<ul>
<h2><a href="<?php echo get_category_link($catid);?>" target="_blank"><?php echo get_cat_name($catid) ?></a></h2>
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>" target="_blank"><?php echo mb_strimwidth(get_the_title(), 0, 38, "..."); ?></a>(
<?php the_time("m-d"); ?>
)</li>
<?php endwhile; ?>
</ul>
</div>
<?php } ?>
将本代码直接复制到主题模板 index.php 中即可读取出所有的分类及文章,我们看一下实现的原理。
get_categories() 得到所有分类列表
然后用遍历数组循环所有分类
$cat->cat_ID;得到分类ID
query_posts得到该分类下最新的10篇文章。