WooCommerce ACF在购物车和结帐页面显示自定义元数据


WooCommerce ACF Display custom meta data on Cart and Checkout page

我想显示与高级自定义字段插件创建的自定义字段的值,同时在WooCommerce购物车和结帐页面。

我在我的主题的 functions.php 页面中使用了下面的代码,它只显示在产品的单个页面中:

add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_field', 0 );
function add_custom_field() {
    global $post;
  echo "<div class='produto-informacoes-complementares'>";
  echo get_field( 'info_complementar', $product_id, true );
  echo "</div>";
    return true;
}

提前感谢大家给予的所有帮助,请原谅我的英语。

我不能在你的网店上测试这个,所以我不能完全确定:

在单个产品页面显示自定义字段值(您的功能):

add_action( 'woocommerce_before_add_to_cart_button', 'add_product_custom_field', 0 );
function add_product_custom_field() {
    global $product;
    if ( $info_complementar = get_field( 'info_complementar', $product->get_id() ) ) {
        echo '<div class="produto-informacoes-complementares">' . $info_complementar . '</div>';
    }
}

将自定义字段存储到购物车和会话中:

add_filter( 'woocommerce_add_cart_item_data', 'save_my_custom_product_field', 10, 2 );
function save_my_custom_product_field( $cart_item_data, $product_id ) {
    if( $info_complementar = get_field( 'info_complementar', $product_id ) ) 
    {
        $cart_item_data['info_complementar'] = $info_complementar;
        // below statement make sure every add to cart action as unique line item
        $cart_item_data['unique_key'] = md5( microtime().rand() );
    }
    return $cart_item_data;
}

在购物车和结帐上呈现meta:

add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2 );
function render_meta_on_cart_and_checkout( $cart_data, $cart_item ) {
    $custom_items = array();
    if( !empty( $cart_data ) ) {
        $custom_items = $cart_data;
    }
    if( isset( $cart_item['info_complementar'] ) ) {
        $custom_items[] = array( 
            'name' => __("Info complementar"), 
            'value' => $cart_item['info_complementar'] 
        );
    }
    return $custom_items;
}

最后两个挂钩有一些错误,造成麻烦,现在应该可以了。


添加:

在订单表后的订单详细页面显示ACF值

add_action ('woocommerce_order_details_after_order_table', 'action_order_details_after_order_table', 20 );
function action_order_details_after_order_table($order) {
    foreach ( $order->get_items() as $item ) {
        if ( $info_complementar = get_field('info_complementar', $item->get_product_id())) {
            printf('<p class="info-complementar">%s: %s<p>', __("Info complementar"), $info_complementar);
        }
    }
}