wordpress分类列表页面显示该分类下的子分类文章列表

WordPress教程 13582

给客户仿制一个网站,需要在分类列表页面下调用显示该分类目录下的所有子分类的各自文章列表,该显示效果在很多CMS网站中很常见也很流行!对于wordpress程序,创建好网站的分类和相关子分类后,可以通过下面的代码实现,该代码可以实现当目前分类下存在子分类的时候,则分类列表页面列出所有子分类的各自文章列表,如果当前分类下不存在子分类的时候,则显示该分类的文章列表!

wordpress分类列表页面显示该分类下的子分类文章列表

把以下代码调整后添加到主题的category.php文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?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(); ?>">全文阅读>></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>';
        }
    }
}
?>

代码来自:Wopus问答

精品推荐: