php ACF分类顺序

xe55xuns  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(105)

我已经创建了一个ACF分类字段,用于选择Woocommerce产品类别。它具有多选外观,我想按多选顺序排列分类。
它是工作,但只显示在字母顺序。我错过了一些东西,但无法找到解决方案。
这是我使用的代码:

<?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; ?>
zvokhttg

zvokhttg1#

可以使用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');

相关问题