在之前的網站製作文章中講到了 WordPress 如何呼叫當前分類下面的子分類的方法,但這種方法只能呼叫出子分類的名稱,無法去呼叫出子分類下面的文章列表。 (相關閱讀:WordPress 呼叫分類下的二級分類名)

在做網站時,為了實現某種需要,我們要同時呼叫出分類的名稱和文章列表,以達到如下圖的效果。

為達到這樣的功能,我們需要判斷一下當前分類包含的二級子分類,然後呼叫出所有的二級分類 ID,再透過 ID 去呼叫子分類的名稱和子分類下面的文章列表。程式碼如下:

[php] <?php
global $cat;
$cats = get_categories(array(
'child_of' => $cat,
'parent' => $cat,
'hide_empty' => 0
));
$c = get_category($cat);
if(empty($cats)){
?>
<div class="item">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="post">
<h2><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
<p><a href="<?php the_permalink(); ?>">more >></a></p>
<div class="meta"><?php the_time('Y-m-d'); ?> | 標籤: <?php the_tags('', ' , ', ''); ?></div>
</div>
<?php endwhile; ?>
<?php else: ?>
<div class="post"><p> 暫無文章</p></div>
<?php endif; ?>
</div>
<div class="navigation">
<span class="alignleft"><?php next_posts_link('&laquo; Older posts') ?></span>
<span class="alignright"><?php previous_posts_link('Newer posts &raquo;') ?></span>
</div>
<?php
}else{
foreach($cats as $the_cat){
$posts = get_posts(array(
'category' => $the_cat->cat_ID,
'numberposts' => 10,
));
if(!empty($posts)){
echo '
<div class="item cat_item">
<div class="item_title"><h2><a title="'.$the_cat->name.'" href="'.get_category_link($the_cat).'">'.$the_cat->name.'</a></h2></div>
<ul class="box_list">';
foreach($posts as $post){
echo '<li><span class="alignright">'.mysql2date('Y-m-d', $post->post_date).'</span>
<a title="'.$post->post_title.'" href="'.get_permalink($post->ID).'">'.$post->post_title.'</a></li>';
}
echo '</ul>
</div>';
}
}
}
?>[/php]