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

如何修改WooCommerce商品属性展示短代码实现按slug排序

实现属性按slug排序的修改后代码

/**
 * Attributes shortcode callback.
 */
function so_39394127_attributes_shortcode( $atts ) {

    global $product;

    if( ! is_object( $product ) || ! $product->has_attributes() ){
        return;
    }

    // parse the shortcode attributes
    $args = shortcode_atts( array(
        'attributes' => array_keys( $product->get_attributes() ), // by default show all attributes
    ), $atts );

    // is pass an attributes param, turn into array
    if( is_string( $args['attributes'] ) ){
        $args['attributes'] = array_map( 'trim', explode( '|' , $args['attributes'] ) );
    }

    // 收集所有有效的属性分类法并按slug排序
    $valid_taxonomies = [];
    foreach ( $args['attributes'] as $attribute ) {
        $taxonomy = strpos( $attribute, 'pa_' ) === false ? wc_attribute_taxonomy_name( $attribute ) : $attribute;
        if( taxonomy_is_product_attribute( $taxonomy ) ){
            $valid_taxonomies[] = $taxonomy;
        }
    }
    // 按taxonomy的slug排序属性项的展示顺序,不需要可以删除下面这行
    usort($valid_taxonomies, function($a, $b) {
        return strcmp($a, $b);
    });

    // start with a null string because shortcodes need to return not echo a value
    $html = '';

    if( ! empty( $valid_taxonomies ) ){

        foreach ( $valid_taxonomies as $taxonomy ) {

            // Get the attribute label.
            $attribute_label = wc_attribute_label( $taxonomy );

            // 查询该属性下当前商品的术语,按slug排序
            $terms = get_terms([
                'taxonomy' => $taxonomy,
                'object_ids' => [$product->get_id()],
                'orderby' => 'slug',
                'order' => 'ASC',
                'hide_empty' => false,
            ]);

            if (!is_wp_error($terms) && !empty($terms)) {
                $term_links = [];
                foreach ($terms as $term) {
                    $term_links[] = '<a href="' . get_term_link($term) . '">' . $term->name . '</a>';
                }
                $terms_html = implode(', ', $term_links);
                $html .= '<li class="bullet-arrow">' . $attribute_label . ': ' . $terms_html . '</li>';
            }
        }

        // if we have anything to display, wrap it in a <ul> for proper markup
        // OR: delete these lines if you only wish to return the <li> elements
        if( $html ){
            $html = '<ul class="product-attributes">' . $html . '</ul>';
        }

    }

    return $html;
}
add_shortcode( 'display_attributes', 'so_39394127_attributes_shortcode' );

修改说明

  • 替换了原代码中直接调用get_the_term_list()的逻辑,改为手动查询属性术语,查询参数指定orderby为slug,实现每个属性下的属性值按slug升序排列
  • 新增了属性项本身的排序逻辑:所有要展示的属性会先按其分类法slug排序后再遍历输出,如果不需要调整属性项的展示顺序,直接删除代码中usort相关的代码段即可
  • 输出结构和原代码完全一致,不会影响原有页面样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:15:03