ACF 分类顺序

问题描述 投票:0回答:1

我创建了一个选择 Woocommerce 产品类别的 ACF 分类法字段。它具有多选外观,我想按多选顺序对分类法进行排序。

它正在工作,但仅按字母顺序显示。 我遗漏了一些东西,但找不到解决方案。

这是我使用的代码:

<?php $terms = get_the_terms( get_the_ID(), 'product_cat' );
            ?>

            <?php if( $terms ): 
                ?>
                <?php foreach( $terms as $term ): ?>
                <div class="col order-">
                    <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 $image; ?>" class="" alt="...">
                        </div>
                        <?php if( $term->description ): ?>
                        <div class="card-img-overlay d-flex">
                            <div class="card-text">
                                <p class=""><?php echo $term->description; ?></p>
                            </div>
                        </div>
                        <?php endif; ?>
                        <a class="stretched-link " href="<?php echo get_term_link( $term->term_id ); ?>"></a>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
php wordpress advanced-custom-fields taxonomy
1个回答
0
投票

您可以使用 wp_get_object_terms() 函数。

$terms = wp_get_object_terms(get_the_ID(), 'product_cat', ['orderby' => 'name', 'order' => 'ASC'])

orderBy 和 order 的参考可能值 https://developer.wordpress.org/reference/classes/wp_term_query/__construct/

但是,此函数不应用缓存。如果要应用缓存,可以考虑写一个自定义函数,如下所示:

function get_the_terms_by_order( $post, $taxonomy, $orderBy = 'name', $order = 'ASC') {
    $post = get_post( $post );

    if ( ! $post ) {
        return false;
    }

    $terms = get_object_term_cache( $post->ID, $taxonomy );

    if ( false === $terms ) {
        $terms = wp_get_object_terms( $post->ID, $taxonomy, ['orderBy' => $orderBy, 'order' => $order] );
        if ( ! is_wp_error( $terms ) ) {
            $term_ids = wp_list_pluck( $terms, 'term_id' );
            wp_cache_add( $post->ID, $term_ids, $taxonomy . '_relationships' );
        }
    }

    if ( empty( $terms ) ) {
        return false;
    }

    return $terms;
}

然后:

$terms = get_the_terms_by_order( $post, $taxonomy, 'name', 'DESC');
© www.soinside.com 2019 - 2024. All rights reserved.