如何修改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
相关产品推荐
相关产品推荐

