php - 如何更改 WooCommerce 产品的产品标签列表中的排序

标签 php wordpress woocommerce product taxonomy-terms

我使用此函数来获取并显示每个产品的所有标签:

public function get_product_tags_list() {
            global $product;

            if ( ! is_a( $product, 'WC_Product' ) ) {
                return;
            }

            $separator = '<span class="separator">&#44;&nbsp;</span></li><li>';
            $before    = '<ul><li>';
            $after     = '</li></ul>';

            return get_the_term_list( $product->get_id(), 'product_tag', $before, $separator, $after );
        }

如何按 slug 降序对标签列表进行排序?

问候

最佳答案

允许更改排序选项的唯一方法是基于 WordPress get_the_term_list() 核心函数源代码构建您自己的函数,将函数 get_the_terms() 替换为 wp_get_post_terms() 允许附加参数更改 WP_Term_Query,如下所示:

public function get_product_tags_list() {
    global $product;

    if ( ! is_a( $product, 'WC_Product' ) ) {
        return;
    }

    $taxonomy  = 'product_tag'; // The taxonomy
    $args      = array( // Your sorting parameters below
        'orderby' => 'slug',
        'order'   => 'DESC',
    );

    $terms = wp_get_post_terms( $product->get_id(), $taxonomy, $args );
    
    if ( is_wp_error( $terms ) ) {
        return $terms;
    }
 
    if ( empty( $terms ) ) {
        return false;
    }
            
    $links = array();
 
    foreach ( $terms as $term ) {
        $link = get_term_link( $term, $taxonomy );
        
        if ( is_wp_error( $link ) ) {
            return $link;
        }
        $links[] = '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
    }
    $term_links = apply_filters( "term_links-{$taxonomy}", $links );  // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
    
    $separator = '<span class="separator">&#44;&nbsp;</span></li><li>';
    $before    = '<ul><li>';
    $after     = '</li></ul>';
    
    return $before . join( $separator, $term_links ) . $after;
}

代码位于事件子主题(或事件主题)的functions.php 文件中。它应该有效。


文档:

关于php - 如何更改 WooCommerce 产品的产品标签列表中的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65005503/

相关文章:

javascript - 使用 JavaScript 提交 HTML 表单

javascript - 从没有 ID 的 Img 中获取 id

html - 以 Wordpress 为中心的导航

php - 列名称中的单引号 - 如何选择值

wordpress - 将自定义 TiniMCE 按钮添加到第二行?

WordPress theme-functions.php 中的 PHP 和 MYSQL 脚本用于提取和回显数据

php - 在 WooCommerce 格式的产品尺寸输出中包含尺寸字母 L/W/H

php - 将 Woocommerce 订阅更新和同步到自定义日期

ajax - 使用ajax添加优惠券时如何禁止购物车页面显示优惠券通知?

使用 HTTP header 上传 PHP 文件