在 Woocommerce 购物车和结帐中显示特定的父产品属性

Display specific parent product attribute in Woocommerce cart and checkout

我为我的产品分配了金属类型属性,但未用作变体的一部分,我仍想获取每个父产品的金属类型并将其显示在 cart/checkout 页面中。

要获取所选金属类型术语的名称,我使用以下内容:

$_product = $cart_item['data]'];
$parent_id = $_product->get_parent_id();
$parent_attributes = wc_get_product($parent_id)->get_attributes();
$term_id = $parent_attributes['pa_metal-type']['data']['options'][0];
$term = get_term_by('id', $termId, 'pa_metal-type');
$term_name = $term->name;

我尝试使用 woocommerce_get_item_data 过滤器似乎没有用,我知道我在某个地方犯了错误,但我没有足够的经验知道在哪里:

// Add metal type to cart line items
add_filter( 'woocommerce_get_item_data', 'get_metal_type', $cart_data, $cart_item );

function get_metal_type($cart_data, $cart_item) {

  $_product = $cart_item['data]'];
  $parent_id = $_product->get_parent_id();
  $parent_attributes = wc_get_product($parent_id)->get_attributes();
  $term_id = $parent_attributes['pa_metal-type']['data']['options'][0];
  $term = get_term_by('id', $termId, 'pa_metal-type');
  $term_name = $term->name;

  $custom_items = array();

  if( !empty( $cart_data ) ) { $custom_items = $cart_data; }

  if( !empty($term) ) {

      $custom_items[] = array(
          'key'   => 'Metal Type',
          'value' => $term_name,
        );

      return $custom_items;

  }
}

任何见解将不胜感激!

你把事情搞得比实际情况复杂得多。请尝试以下操作:

// Display the Meta type in cart and checkout
add_filter( 'woocommerce_get_item_data', 'display_attribute_metal_type', 90, 2 );
function display_attribute_metal_type( $cart_item_data, $cart_item ){
    if( $cart_item['variation_id'] > 0 ) {
        // Get the parent variable product object instance
        $product = wc_get_product( $cart_item['product_id'] );

        // Get the "Metal type" product attribute term name
        $term_names = $product->get_attribute( 'metal-type' );

        if( isset($term_names) && ! empty($term_names) ){
            // Add "Metal type" data to be displayed
            $cart_item_data[] = array(
                'name' => __('Metal Type'),
                'value' => $term_names,
            );
        }
    }
    return $cart_item_data;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。