【问题标题】:Woocommerce - Show and sort attributes in codeWoocommerce - 在代码中显示和排序属性
【发布时间】:2021-09-06 22:03:15
【问题描述】:

我在这里找到了用于在产品页面上显示 WooCommerce 产品属性的代码:Woocommerce - Display single product attribute(s) with shortcodes in Frontend_

我知道有一些方法可以在 WooCommerce 后端对属性进行排序,但我无法让它们按应有的方式工作。我看到很多人对属性的排序有问题。有没有办法通过修改此代码使它们按“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'] ) );
    }

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

    if( ! empty( $args['attributes'] ) ){

        foreach ( $args['attributes'] as $attribute ) {

            // get the WC-standard attribute taxonomy name
            $taxonomy = strpos( $attribute, 'pa_' ) === false ? wc_attribute_taxonomy_name( $attribute ) : $attribute;

            if( taxonomy_is_product_attribute( $taxonomy ) ){

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

                // Build the html string with the label followed by a clickable list of terms.
                // Updated for WC3.0 to use getters instead of directly accessing property.
                $html .= get_the_term_list( $product->get_id(), $taxonomy, '<li class="bullet-arrow">' . $attribute_label . ': ' , ', ', '</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' );

【问题讨论】:

    标签: wordpress woocommerce attributes


    【解决方案1】:

    如果有人还在寻找答案,如果您添加

    sort($args['attributes']);
    

    在foreach循环之前,会对属性slug显示的属性进行排序

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多