菜鸟笔记
提升您的技术认知

按 WordPress 分类展示文章列表

通过下面的代码可以实现WordPress文章按分类展示文章列表,将代码放在分类归档页面,当该分类有子分类时,则显示子分类文章列表,无子分类则显示该分类列表,将代码放在首页,则所有文章按分类以列表形式展示。

$current_cat = get_queried_object();
echo '父分类名称: '.$current_cat->name;
$subcategories = get_categories(
    array( 'parent' => $current_cat->term_id )
);

// 判断是否有子分类
if( !empty( $subcategories ) ) {
    foreach( $subcategories as $cat ) {
        echo '<br><b>分类名称: '.$cat->name.'</b><br>';
        $cat_posts = get_posts( array(
            'posts_per_page' => -1,
            'category'       => $cat->term_id
        ) );

        if ( $cat_posts ) {
            foreach ( $cat_posts as $post ) :
                echo '<a href="'.get_permalink().'">'.$post->post_title.'</a><br>';
            endforeach;
        }
    }
} else {
    $cat_posts = get_posts( array(
        'posts_per_page' => -1,
        'category'       => $current_cat->term_id
    ) );

    if ( $cat_posts ) {
        foreach ( $cat_posts as $post ) :
            echo '<a href="'.get_permalink().'">'.$post->post_title.'</a><br>';
        endforeach;
    }
}