在Woocommerce购物车页面上显示特定产品属性

时间:2020-08-25 08:29:35

标签: php wordpress woocommerce

我想在表中产品名称下方的Woocommerce购物车页面和结帐页面上显示特定的产品属性。

custom_display_attribute

1 个答案:

答案 0 :(得分:1)

您可以使用以下过滤器在购物车页面上显示属性。参考链接:https://isabelcastillo.com/show-woocommerce-product-attributes-on-cart-page

/**
* WooCommerce: show all product attributes, separated by comma, on cart page
*/
function isa_woo_cart_attribute_values( $cart_item, $cart_item_key ) {
  
    $item_data = $cart_item_key['data'];
    $attributes = $item_data->get_attributes();
      
    if ( ! $attributes ) {
        return $cart_item;
    }
      
    $out = $cart_item . '<br />';
      
    $count = count( $attributes );
      
    $i = 0;
    foreach ( $attributes as $attribute ) {
   
        // skip variations
        if ( $attribute->get_variation() ) {
             continue;
        }
   
        $name = $attribute->get_name();          
        if ( $attribute->is_taxonomy() ) {
 
            $product_id = $item_data->get_id();
            $terms = wp_get_post_terms( $product_id, $name, 'all' );
               
            // get the taxonomy
            $tax = $terms[0]->taxonomy;
               
            // get the tax object
            $tax_object = get_taxonomy($tax);
               
            // get tax label
            if ( isset ( $tax_object->labels->singular_name ) ) {
                $tax_label = $tax_object->labels->singular_name;
            } elseif ( isset( $tax_object->label ) ) {
                $tax_label = $tax_object->label;
                // Trim label prefix since WC 3.0
                $label_prefix = 'Product ';
                if ( 0 === strpos( $tax_label,  $label_prefix ) ) {
                    $tax_label = substr( $tax_label, strlen( $label_prefix ) );
                }
            }
            $out .= $tax_label . ': ';
 
            $tax_terms = array();              
            foreach ( $terms as $term ) {
                $single_term = esc_html( $term->name );
                array_push( $tax_terms, $single_term );
            }
            $out .= implode(', ', $tax_terms);
              
            if ( $count > 1 && ( $i < ($count - 1) ) ) {
                $out .= ', ';
            }
          
            $i++;
            // end for taxonomies
      
        } else {
  
            // not a taxonomy
              
            $out .= $name . ': ';
            $out .= esc_html( implode( ', ', $attribute->get_options() ) );
          
            if ( $count > 1 && ( $i < ($count - 1) ) ) {
                $out .= ', ';
            }
          
            $i++;
              
        }
    }
    echo $out;
}
add_filter( 'woocommerce_cart_item_name', isa_woo_cart_attribute_values, 10, 2 );