1
votes

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.

1

1 Answers

5
votes

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_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( 'info_complementar', $product_id );
    echo "</div>";

    return true;
}

(updated) 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( 'info_complementar', $product_id, true );

    if( !empty( $custom_field_value ) ) 
    {
        $cart_item_data['info_complementar'] = $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;
}

(updated) 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['info_complementar'] ) ) {
        $custom_items[] = array( "name" => "Info complementar", "value" => $cart_item['info_complementar'] );
    }
    return $custom_items;
}

There was some mistakes in the 2 last hooks that was making this not working… Now it should work.