Reputation: 73
I would like to show the value of my custom field created with Advanced Custom Fields plugin, at the same time in WooCommerce cart and checkout pages.
I'm using the code below in the functions.php
page of my theme, which displays only in the single page of the product:
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;
}
Thank you all in advanced for all the help given and excuse my english.
Upvotes: 1
Views: 5349
Reputation: 253784
I can't test this on your web shop, so I am not completely sure:
Displaying custom field value in single product page (your function):
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>';
}
}
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 ) {
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;
}
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();
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;
}
There were some mistakes in the 2 last hooks, making trouble… Now it should work.
Addition:
Display ACF value in order detail page after order table
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);
}
}
}
Upvotes: 5