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

在自定义分类法colture归档页按顶级默认分类分组文章

嘿,我来帮你搞定这个需求!结合你已有的循环逻辑,我们可以通过先锁定那3个顶级默认分类,再在每个分类下筛选当前colture术语关联的文章,同时保留你原本每3篇文章一个div的分组规则。下面是具体的实现思路和代码:

实现步骤与代码示例

首先,我们需要明确用来分组的3个顶级默认分类(你可以用slug或ID来指定),然后在单个colture术语页面中,针对每个默认分类筛选出符合条件的文章,同时嵌入你已有的文章分组逻辑。

<?php
// 获取当前访问的colture术语对象
$current_colture_term = get_queried_object();

// 定义要用来分组的3个顶级默认分类(替换成你实际的分类slug)
$target_top_categories = ['cat-slug-1', 'cat-slug-2', 'cat-slug-3'];

// 遍历每个目标分类,生成分组内容
foreach ($target_top_categories as $cat_slug) {
    // 通过slug获取分类对象,不存在则跳过
    $category = get_category_by_slug($cat_slug);
    if (!$category) continue;

    // 输出带titolo-applicazioni类的h1标题
    echo '<h1 class="titolo-applicazioni">' . esc_html($category->name) . '</h1>';

    // 构建查询参数:同时属于当前colture术语和目标默认分类的文章
    $group_post_args = [
        'post_type' => 'post', // 如果你的文章是自定义类型,替换成对应的slug
        'tax_query' => [
            'relation' => 'AND',
            [
                'taxonomy' => 'colture',
                'field' => 'term_id',
                'terms' => $current_colture_term->term_id,
            ],
            [
                'taxonomy' => 'category',
                'field' => 'term_id',
                'terms' => $category->term_id,
            ],
        ],
        'posts_per_page' => -1, // 获取所有符合条件的文章
        'orderby' => 'date', // 可根据需求调整排序规则
        'order' => 'DESC',
    ];

    $group_posts_query = new WP_Query($group_post_args);

    // 初始化文章计数器,用来控制每3篇一组的div
    $post_counter = 0;

    if ($group_posts_query->have_posts()) {
        while ($group_posts_query->have_posts()) {
            $group_posts_query->the_post();

            // 每3篇文章的开头输出分组div(替换成你已有的div类名)
            if ($post_counter % 3 === 0) {
                echo '<div class="your-existing-post-group-class">';
            }

            // 这里插入你原本的文章内容模板(标题、缩略图、摘要等)
            ?>
            <article class="your-post-item-class">
                <h3><?php the_title(); ?></h3>
                <?php the_post_thumbnail('medium'); ?>
                <div class="post-excerpt"><?php the_excerpt(); ?></div>
            </article>
            <?php

            $post_counter++;

            // 每3篇闭合div,最后一组不足3篇时也闭合
            if ($post_counter % 3 === 0 || $post_counter === $group_posts_query->post_count) {
                echo '</div>';
            }
        }
        wp_reset_postdata(); // 重置查询,避免影响后续页面逻辑
    } else {
        // 分类下无文章时的提示(可根据需求修改或删除)
        echo '<p>暂无相关文章</p>';
    }
}
?>

关键调整提示:

  • 把$target_top_categories里的slug替换成你实际要分组的3个顶级默认分类slug
  • 如果你的文章是自定义类型,修改post_type参数为对应的值
  • 替换your-existing-post-group-class和your-post-item-class为你已有的div和文章项类名
  • 排序规则orderby和order可以根据需求调整(比如按标题排序)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:06:26