【问题标题】:Display specific parent product attribute in Woocommerce cart and checkout在 Woocommerce 购物车和结帐中显示特定的父产品属性
【发布时间】:2018-08-05 05:15:58
【问题描述】:

我有一个金属类型属性分配给我的产品,但不用作变体的一部分,我仍然想获取每个父产品的金属类型并将其显示在购物车/结帐页面中。

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

$_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;

  }
}

任何见解将不胜感激!

【问题讨论】:

    标签: php wordpress woocommerce cart checkout


    【解决方案1】:

    你做的比现在复杂得多。请尝试以下方法:

    // 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 文件中。经过测试并且可以工作。

    【讨论】:

    • 测试了解决方案,它似乎工作得很好!我不知道我可以获得该属性,即使它没有分配给变体本身。此外,解决您的解决方案,对于具有单个属性(例如颜色)的产品,函数 wc_get_formatted_cart_item_data 似乎不会输出颜色属性及其术语,但对于具有两个属性(例如颜色、尺寸)的产品输出两个属性及其项。
    猜你喜欢
    • 1970-01-01
    • 2020-12-13
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 2016-12-13
    • 1970-01-01
    • 2019-05-11
    相关资源
    最近更新 更多