我正在使用 Woocommerce、Snippets 和 ACF 字段,我在产品中创建了元字段,我想在购物车项目中获取 ACF 字段,并将它们保存在订单表中但不起作用,我已经检查了大页面但我仍然没有找不到我需要的答案,你能帮帮我吗?提前致谢。
我试过了
add_action( 'woocommerce_get_cart_item_from_session', 'cart_item_from_session' , 99, 2 );
function cart_item_from_session( $item_id, $data ) {
$calories = $item_id->get_meta('acf-calories');
$delivery_date = $item_id->get_meta('acf-delivery_date');
}
add_filter( 'woocommerce_add_order_item_meta', 'add_item_meta_order', 10, 3 );
function add_item_meta_order( $item_id, $data ) {
wc_add_order_item_meta( $item_id, 'acf-calories', "$calories", 'acf-delivery_date', "$delivery_date");
}
// Display on product page
add_action( 'woocommerce_before_add_to_cart_button', 'display_acf_single_product_pages', 1 );
function display_acf_single_product_pages() {
global $product;
$calories = get_field( 'acf-calories', $product->get_id() );
$delivery_date = get_field( 'acf-delivery_date', $product->get_id() );
}
// Add as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'save_acf_as_cart_item_data', 10, 2 );
function save_acf_as_cart_item_data( $cart_item_data, $cart_item ) {
$calories = $item_id->get_meta('acf-calories');
$delivery_date = $item_id->get_meta('acf-delivery_date');
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
// Display on cart and checkout
add_filter( 'woocommerce_get_item_data', 'display_acf_on_cart_and_checkout', 10, 2 );
function display_acf_on_cart_and_checkout( $cart_data, $cart_item ) {
$calories = $item_id->get_meta('acf-calories');
$delivery_date = $item_id->get_meta('acf-delivery_date');
//I don't know if here I have to add some return?
}
// Display on orders and email notifications (save as custom order item meta data)
add_action( 'woocommerce_checkout_create_order_line_item', 'display_acf_on_orders_and_emails', 10, 4 );
function display_acf_on_orders_and_emails( $item, $cart_item_key, $values, $order ) {
$calories = get_field( 'acf-calories', $values['product_id'] );
$delivery_date = get_field( 'acf-delivery_date', $values['product_id'] );
}
// Change displayed label for specific custom order item meta keys
add_filter('woocommerce_order_item_display_meta_key', 'filter_wc_order_item_display_meta_key', 10, 3 );
function filter_wc_order_item_display_meta_key( $display_key, $meta, $item ) {
// Change displayed label for specific order item meta key
if( is_admin() && $item->get_type() === 'line_item' ) {
if( $meta->key === 'acf-calories' ) {
$display_key = __("Calories", "woocommerce");
}
if( $meta->key === 'acf-delivery_date' ) {
$display_key = __("Delivery Date", "woocommerce");
}
}
return $display_key;
}