PHP Snippet 1:
//Displaying custom field value in single product page
add_action( 'woocommerce_single_product_summary', 'add_custom_field', 0 );
function add_custom_field() {
global $product; // Changed this
// Added this too (compatibility with WC +3)
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
echo "<div class='produto-informacoes-complementares'>";
echo get_field( 'brand_name', $product_id );
echo "</div>";
return true;
}
PHP Snippet 2:
// Storing this custom field into cart and session:
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 ) {
$custom_field_value = get_field( 'brand_name', $product_id, true );
if( !empty( $custom_field_value ) )
{
$cart_item_data['brand_name'] = $custom_field_value;
// 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;
}
PHP Snippet 3:
//Render meta on cart and checkout
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();
// Woo 2.4.2 updates
if( !empty( $cart_data ) ) {
$custom_items = $cart_data;
}
if( isset( $cart_item['brand_name'] ) ) {
$custom_items[] = array( "name" => "Brand Name", "value" => $cart_item['brand_name'] );
}
return $custom_items;
}
PHP Snippet 4:
//Display Filed Value on Mail tamplate
function add_order_item_meta_acf( $item_id, $values ) {
wc_add_order_item_meta( $item_id, 'Brand Name', $values [ 'brand_name' ] );
}
add_action( 'woocommerce_add_order_item_meta', 'add_order_item_meta_acf' , 10, 2);