首页 > 解决方案 > 如何在 WooCommerce 订单项中获取 ACF 产品字段值

问题描述

下订单后,我正在修改我的商店以在 WooCommerce 订单页面上显示自定义字段。

我的代码被插入到 default/themes/mytheme/woocommerce/order/order-details-item.php中。这是读取字段的部分:

$per_unit_or_square = get_field('pricem2_or_priceunit_', $product->get_id());

if (!empty($per_unit_or_square)) {
    if ($per_unit_or_square == 'unit') {
        $pricingtype_order_received = '<span class="pricingtype_order_received">'.__('&nbsp;unit&nbsp;', 'mbb').'</span>';
    } elseif ($per_unit_or_square == 'm2') {
        $pricingtype_order_received = '<span class="pricingtype_order_received">'.__('&nbsp;m<sup>2</sup>&nbsp;', 'mbb').'</span>';
    } else {
        $pricingtype_order_received = '<span class="pricingtype_order_received">'.__('&nbsp;pcs&nbsp;', 'mbb').'</span>';
    }
}

正如您在上面看到的,我正在尝试设置一个变量$pricingtype_order_received并将其放在数量数字之后,以显示客户是否购买了单位 m2 或 pcs:

if ( $refunded_qty ) {
    $qty_display = '<del>' . esc_html( $qty ) . '</del> <ins>' . esc_html( $qty - ( $refunded_qty * -1 ) ) . '</ins>'.$pricingtype_order_received;
} else {
    $qty_display = esc_html( $qty ).$pricingtype_order_received;
}

我的问题是代码不起作用并且没有检索$pricingtype_order_received值。相同的逻辑适用于购物车和其他页面,但不适用于订单,以及订单完成后的电子邮件。

在哪里寻找?ACF 字段是否可以在订单和电子邮件中读取?

如果有人感兴趣,这是整个代码:https ://pastebin.com/PCDs32LC

标签: phpwordpresswoocommerceadvanced-custom-fieldsorders

解决方案


尝试替换$product->get_id()$item->get_product_id()

$per_unit_or_square = get_field( 'pricem2_or_priceunit_', $item->get_product_id() );

相关:在 WooCommerce 3 中获取订单商品和 WC_Order_Item_Product


推荐阅读