我在 woocommerce 产品中添加了一个名为“捐赠”的自定义字段,该字段存储单个产品的捐赠。然后,我添加了名为“line_donation”的订单项元数据。现在我需要在产品数量变化上更新“line_donation”,并在单击更新购物车按钮后更新产品总数变化。
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 );
欢迎任何帮助。