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

ACF分类字段多选排序异常:WooCommerce产品分类未按选择顺序展示

解决ACF多选产品分类按选择顺序展示的问题

你当前使用get_the_terms()获取WooCommerce产品分类的方式,会返回按字母排序的分类集合,这和ACF多选字段的选择顺序不匹配。要保留用户选择时的顺序,需要直接读取ACF字段存储的分类ID列表,再逐个获取对应的分类对象。

修改后的代码示例

假设你的ACF多选字段的字段键为product_categories(请替换为你实际的字段键),修改代码如下:

<?php 
// 直接从ACF字段获取选中的分类ID数组(保持选择顺序)
$selected_term_ids = get_field('product_categories');
?>

<?php if( $selected_term_ids ): ?>
    <?php foreach( $selected_term_ids as $index => $term_id ): 
        // 通过ID获取分类对象
        $term = get_term( $term_id, 'product_cat' );
        if( !$term || is_wp_error($term) ) continue;
    ?>
    <div class="col order-<?php echo $index + 1; ?>">
        <div class="card h-100 pe-auto">
            <div class="card-body">
                <h4 class="card-title"><?php echo $term->name; ?></h4>
            </div>
            <div class="category-img">
                <?php 
                $thumb_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id' );
                $image = wp_get_attachment_url( $thumb_id ); 
                ?>
                <img src="<?php echo esc_url($image); ?>" class="" alt="<?php echo esc_attr($term->name); ?>">
            </div>
            <?php if( $term->description ): ?>
            <div class="card-img-overlay d-flex">
                <div class="card-text">
                    <p class=""><?php echo wp_kses_post($term->description); ?></p>
                </div>
            </div>
            <?php endif; ?>
            <a class="stretched-link" href="<?php echo esc_url(get_term_link( $term->term_id )); ?>"></a>
        </div>
    </div>
    <?php endforeach; ?>
<?php endif; ?>

关键修改说明

  • 用get_field('你的字段键')替代get_the_terms(),直接获取ACF存储的分类ID数组,这个数组的顺序就是用户选择时的顺序。
  • 循环时通过get_term()根据ID获取分类对象,确保拿到正确的分类数据。
  • 添加了esc_url()、esc_attr()、wp_kses_post()等安全函数,避免XSS风险(建议保留)。
  • 给order-类添加了索引值($index + 1),让Bootstrap的排序类生效(如果需要的话)。

注意事项

  1. 确认你替换了代码中的product_categories为你实际的ACF字段键。
  2. 如果ACF字段设置的是返回"分类对象"而不是"分类ID",可以直接用$selected_terms = get_field('product_categories');,然后循环$selected_terms即可,不需要再用get_term()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:10:34