【问题标题】:Product attribute empty value from order item in Woocommerce 3Woocommerce 3中订单项目的产品属性空值
【发布时间】:2018-12-09 03:51:59
【问题描述】:

我知道已经有很多关于这件事的问题,但我无法弄清楚如何从 woocommerce 订单中获取自定义产品属性。这是我尝试过的:

    $order = wc_get_order( $order_id );
    $order_data = $order->get_data();

    foreach ($order->get_items() as $item_key => $item_values) {

    $product = $item_values->get_product(); // Get the product
    $product_id = $item_values->get_product_id(); // the Product id
    $tokens = get_post_meta($product_id, 'Tokens', true);
    }

我也试过了:

    $tokens = $product->get_attribute( 'Tokens' );

    $tokens = array_shift( wc_get_product_terms( $product_id, 'Tokens', array( 'fields' => 'names' ) ) );

我的自定义产品属性的名称为“Tokens”,值为 5000,但我得到一个空返回,

我做错了什么?

【问题讨论】:

  • 当产品属性未设置为变体属性时,可变产品可能会发生这种情况。当您将此父变量产品的产品变体作为订单项目时,您无法从产品变体本身获取任何内容,您需要获取父变量产品,以获取您的产品属性值。
  • @LoicTheAztecso 我该怎么办?

标签: php wordpress woocommerce custom-taxonomy orders


【解决方案1】:

当产品属性未设置为变体属性时,可变产品可能会发生这种情况。

所以当你有一个产品变体作为订单项时,你需要获取父变量product来获取你的产品属性值(如果这个产品属性未设置为变体的属性)

如果是“令牌”产品属性的情况,请尝试以下操作:

$attribute = 'Tokens';
$order     = wc_get_order( 857 );

// Loop through order line items
foreach ( $order->get_items() as $item_id => $item ) {
    $product = $item->get_product(); // Get the WC_Product object

    // For Product Variation type
    if( $item->get_variation_id() > 0 ){
        $parent = wc_get_product($product->get_parent_id());
        $term_names = $parent->get_attribute($attribute);
    }
    // For other Product types
    else {
        $term_names = $product->get_attribute($attribute);
    }

    // Testing display (the string of coma separated term names if many)
    if( ! empty( $term_name ) )
        echo '<p>'.$term_name.'</p>';
}

在 Woocommerce 3+ 中测试和工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2019-05-25
    • 2019-08-29
    相关资源
    最近更新 更多