I am building a site using WooCommerce and Advanced Custom Fields (ACF) plugin. I've created two ACF custom fields with names "plant" and "amount".
I am trying to display them both on front end but currently only the custom field "plant" is displaying everywhere. I've been looking around the net with no luck.
add_action( 'woocommerce_before_add_to_cart_button', '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( 'plant', $product_id );
echo "</div>";
echo "<div class='produto-informacoes-complementares'>";
echo get_field( 'amount', $product_id );
echo "</div>";
return true;
}
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( 'plant', $product_id, true );
$custom_field_value = get_field( 'amount', $product_id, true );
if( !empty( $custom_field_value ) )
{
$cart_item_data['plant'] = $custom_field_value;
$cart_item_data['amount'] = $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;
}
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['plant'] )) {
$custom_items[] = array( "name" => "גודל עציץ", "value" => $cart_item['plant'] );
$custom_items[] = array( "name" => "כמות במגש", "value" => $cart_item['amount'] );
}
return $custom_items;
}
function add_order_item_meta_acf( $item_id, $values ) {
wc_add_order_item_meta( $item_id, 'גודל עציץ', $values [ 'plant' ] );
wc_add_order_item_meta( $item_id, 'גודל עציץ', $values [ 'amount' ] );
}
add_action( 'woocommerce_add_order_item_meta', 'add_order_item_meta_acf' , 10, 2);