You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

分类条件循环开发:父/子分类样式区分及父分类带3篇文章展示

WordPress Category Conditional Loops & Display Solutions

Hey there! Let's tackle your two category-related questions step by step—these are super common needs when building WordPress sites, so I've got you covered.


1. Different Styles for Parent vs Child Categories

You've got two solid approaches here, depending on whether you prefer handling it via PHP logic or pure CSS.

Method 1: Conditional PHP in Your Category Template

Use WordPress's built-in functions to check if the current category is a parent or child, then output different HTML containers for styling.

Add this to your category.php template (or a custom category template):

<?php
// Grab the current category object
$current_cat = get_queried_object();

// Check if it's a parent category (no parent ID)
if ($current_cat->parent === 0) {
    echo '<div class="category-container category-parent">';
} else {
    echo '<div class="category-container category-child">';
}

// Your existing category content (loop, title, etc.) goes here

echo '</div>';
?>

Then style the classes in your CSS:

.category-parent {
    background-color: #f8f9fa;
    padding: 2rem;
    border-radius: 8px;
}

.category-child {
    background-color: #e9ecef;
    padding: 1.5rem;
    border-left: 4px solid #007bff;
}

Method 2: Target Body Classes with CSS

WordPress automatically adds unique classes to the <body> tag for every category page. Parent categories get a category-parent class, and child categories get category-child plus parent-category-{parent-slug}.

You can skip PHP entirely and style directly via CSS:

/* Style parent category pages */
body.category-parent .page-header {
    font-size: 2.5rem;
    color: #2d3748;
}

/* Style all child category pages */
body.category-child .category-description {
    font-style: italic;
    color: #4a5568;
}

/* Target child categories of a specific parent */
body.parent-category-news .category-posts {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1rem;
}

2. Display Parent Categories with 3 Posts Each

To list all top-level parent categories, each paired with its 3 most recent posts, use a custom query. Add this to the template where you want the display (e.g., home.php, a custom page template, or a widget area):

<?php
// Get all top-level parent categories (exclude empty ones)
$parent_cats = get_categories([
    'parent' => 0,
    'hide_empty' => true,
    'orderby' => 'name',
    'order' => 'ASC'
]);

if (!empty($parent_cats)) {
    $cat_number = 1;
    foreach ($parent_cats as $parent_cat) {
        echo '<div class="parent-category-block">';
        // Output numbered parent category title
        echo '<h2>' . $cat_number . '. ' . esc_html($parent_cat->name) . '</h2>';

        // Query 3 posts from this parent category (includes child category posts by default)
        $cat_posts = new WP_Query([
            'category__in' => [$parent_cat->term_id],
            'posts_per_page' => 3,
            'post_status' => 'publish',
            'orderby' => 'date',
            'order' => 'DESC'
            // Uncomment below to ONLY show posts directly in the parent category (exclude children)
            // 'category__and' => [$parent_cat->term_id]
        ]);

        if ($cat_posts->have_posts()) {
            echo '<ul class="category-post-list">';
            while ($cat_posts->have_posts()) {
                $cat_posts->the_post();
                echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
            }
            echo '</ul>';
            // Reset query to avoid breaking main loop
            wp_reset_postdata();
        } else {
            echo '<p>No posts found in this category.</p>';
        }

        echo '</div>';
        $cat_number++;
    }
} else {
    echo '<p>No parent categories available.</p>';
}
?>

Important Notes:

  • Set hide_empty to false if you want to show parent categories even with no posts.
  • The category__in parameter includes posts from the parent and all its child categories. Use category__and instead if you only want posts assigned directly to the parent category.
  • Always call wp_reset_postdata() after custom queries to restore the main loop's context.

内容的提问来源于stack exchange,提问作者Arpan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:24:18