1、使用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可以設定顯示的篇數,可用于在單頁面上顯示全部分類文章。
2、使用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; ?>
3、結合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 結束 -->
4、自定義函數
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;
}