Reputation: 33
I have added a custom field to the woocommerce product named 'Donation', which stores donation of the individual product. Then, I added line item meta named 'line_donation'. Now I need to update 'line_donation' on product quantity change and after clicking update cart Button like product total changes.
function cfwc_add_custom_field_item_data( $cart_item_data, $product_id, $variation_id, $quantity ) {
// Add the item data
$cart_item_data['line_donation'] = get_post_meta($product_id,'donation', true);
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'cfwc_add_custom_field_item_data', 10, 4 );
/**
* Display the custom field value in the cart
* @since 1.0.0
*/
function cfwc_cart_item_name( $name, $cart_item, $cart_item_key ) {
if( isset( $cart_item['line_donation'] ) ) {
$name .= sprintf(
'<p>%s</p>',
esc_html( $cart_item['line_donation'] )
);
}
return $name;
}
add_filter( 'woocommerce_cart_item_name', 'cfwc_cart_item_name', 10, 3 );
function add_line_donation_to_order( $item, $cart_item_key, $values, $order ) {
foreach( $item as $cart_item_key=>$values ) {
if( isset( $values['line_donation'] ) ) {
$item->add_meta_data( __( 'line_donation', 'woocommerce' ), $values['line_donation'], true );
}
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'add_line_donation_to_order', 10, 4 );
Any help is welcome.
Upvotes: 3
Views: 2816
Reputation: 254373
You just simply need to make a little change in your 2 last functions as follows:
add_filter( 'woocommerce_cart_item_name', 'cfwc_cart_item_name', 10, 3 );
function cfwc_cart_item_name( $name, $cart_item, $cart_item_key ) {
if( isset( $cart_item['line_donation'] ) )
$name .= '<p>' . $cart_item['line_donation'] * $cart_item['quantity'] . '</p>';
return $name;
}
add_action( 'woocommerce_checkout_create_order_line_item', 'add_line_donation_to_order', 10, 4 );
function add_line_donation_to_order( $item, $cart_item_key, $values, $order ) {
foreach( $item as $cart_item_key=>$values ) {
if( isset( $values['line_donation'] ) ) {
$item->add_meta_data( __( 'line_donation', 'woocommerce' ), $values['line_donation'] * $values['quantity'], true );
}
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Upvotes: 1