获取指定分类的所有子分类链接、Description、Slug、自定义字段

获取指定分类的所有子分类链接、Description、Slug、自定义字段

已知父分类的 slug 或 ID 时,可以用 get_term_by() 定位父项,再用 get_terms() 查询子项。链接必须由 get_term_link() 生成,不要拼接 /products/{slug}/ 之类的路径。

以下示例假设分类法名为 product_category,父分类 slug 为 hardware

<?php
$taxonomy = 'product_category';
$parent   = get_term_by( 'slug', 'hardware', $taxonomy );

if ( ! $parent instanceof WP_Term ) {
    return;
}

$terms = get_terms(
    array(
        'taxonomy'   => $taxonomy,
        'parent'     => $parent->term_id,
        'hide_empty' => false,
        'orderby'    => 'name',
    )
);

if ( is_wp_error( $terms ) ) {
    return;
}
?>

<ul class="product-categories">
    <?php foreach ( $terms as $term ) : ?>
        <?php
        $url = get_term_link( $term );

        if ( is_wp_error( $url ) ) {
            continue;
        }

        $icon_id = (int) get_term_meta(
            $term->term_id,
            'category_icon_id',
            true
        );
        ?>

        <li>
            <a href="<?php echo esc_url( $url ); ?>">
                <?php
                if ( $icon_id ) {
                    echo wp_get_attachment_image(
                        $icon_id,
                        'thumbnail',
                        false,
                        array(
                            'alt' => $term->name,
                        )
                    );
                }
                ?>

                <span>
                    <?php echo esc_html( $term->name ); ?>
                </span>
            </a>

            <code><?php echo esc_html( $term->slug ); ?></code>

            <?php if ( $term->description ) : ?>
                <div class="term-description">
                    <?php
                    echo wp_kses_post(
                        term_description(
                            $term->term_id,
                            $taxonomy
                        )
                    );
                    ?>
                </div>
            <?php endif; ?>
        </li>
    <?php endforeach; ?>
</ul>

使用 ACF 分类字段

若图标由 ACF 管理,建议把图片字段的返回格式设为“图片 ID”。模板仍可交给 WordPress 生成 srcset、宽高和合适尺寸:

$icon_id = (int) get_field(
    'category_icon',
    $term
);

if ( $icon_id ) {
    echo wp_get_attachment_image(
        $icon_id,
        'thumbnail'
    );
}

ACF 也支持 {$taxonomy}_{$term_id} 形式,但直接传 WP_Term 可读性更好。字段不存在时要有无图状态,不要假设数组下标一定存在。

常见问题

  • description 可能包含允许的 HTML,输出时使用 wp_kses_post(),名称和 slug 则使用 esc_html()
  • WordPress Core 的 term 默认没有通用 menu_order;需要人工排序时,应使用经过审计的排序插件或明确的 term meta,再实现对应查询策略。
  • get_term_link() 可能返回 WP_Error,不要直接传给 esc_url()
  • 如果只需要 ID 或 slug,可使用 fields 减少返回数据。
  • 分类数量大时,应分页或缓存;后台每次请求遍历全部分类会拖慢页面。
  • 分类层级属于内容数据,不应该从 URL 层级反推。

官方参考:get_terms()get_term_meta()wp_get_attachment_image()

最后更新于

ihopeful Blog 由博主亲笔撰写,重要信息可放心引用。