问题
OK, so basically we created a custom field using ACF in our WooCommerce Store in order to add a "Shipping Delay" notice for specific products.
Here is a demonstration of what we achieved: https://www.safe-company.com/shop/machines/uvc-disinfection-lamp/
Single Product Page Reference Image
We managed then to put this notice in the single product page using Elementor (A page builder) and then add this information to the item data in the cart and checkout page with the following code added to our functions.php
// Render the custom product field in cart and checkout
add_filter( 'woocommerce_get_item_data', 'wc_add_shipping_delay', 10, 2 );
function wc_add_shipping_delay( $cart_data, $cart_item )
{
$custom_items = array();
if( !empty( $cart_data ) )
$custom_items = $cart_data;
// Get the product ID
$product_id = $cart_item['product_id'];
if( $custom_field_value = get_post_meta( $product_id, 'shipping_delay_for_out_of_stock_items', true ) )
$custom_items[] = array(
'name' => __( 'Shipping Delay', 'woocommerce' ),
'value' => $custom_field_value,
'display' => $custom_field_value,
);
return $custom_items;
}
Custom Field in Item Meta from Cart Page
Our problem now is that we need to add this shipping delay notice to the email (show it below each item that contains this data respectively) and on the order page too. How could that be done? Since I have checked a bunch of threads on this but all of them are done using dynamic fields (that the user completes when purchasing) but our case scenario is quite different.
Please help!!
回答1:
The following will save your custom field as order item meta data and display it everywhere:
// Save and display "shipping delay" on order items everywhere
add_filter( 'woocommerce_checkout_create_order_line_item', 'action_wc_checkout_create_order_line_item', 10, 4 );
function action_wc_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
// Get the shipping delay
$value = $values['data']->get_meta( 'shipping_delay_for_out_of_stock_items' );
if( ! empty( $value ) ) {
// Save it and display it
$item->update_meta_data( __( 'Shipping Delay', 'woocommerce' ), $value );
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
来源:https://stackoverflow.com/questions/63025782/save-and-display-product-custom-meta-on-woocommerce-orders-and-emails