这可以通过连接自定义函数轻松完成
woocommerce_add_cart_item_data
过滤器挂钩,一旦产品通过GET请求添加到购物车,它将在购物车项目中存储您的自定义数据。
您可以选择使用第二个挂钩函数在购物车和结帐上显示该数据。这还将允许您检查购物车项目中的数据设置是否正确。
代码:
// Set custom data as custom cart data in the cart item
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_data_in_cart_object', 30, 3 );
function save_custom_data_in_cart_object( $cart_item_data, $product_id, $variation_id ) {
if( ! isset($_GET['custom_price']) || ! isset($_GET['custom_reference_meta']) )
return $cart_item_data; // Exit
// Get the data from the GET request
$custom_price = esc_attr( $_GET['custom_price'] );
$custom_reference_meta = esc_attr( $_GET['custom_reference_meta'] );
// Set the data as custom cart data for the cart item
$cart_item_data['custom_data']['custom_price'] = esc_attr( $_GET['custom_price'] );
$cart_item_data['custom_data']['custom_reference_meta'] = esc_attr( $_GET['custom_reference_meta'] );
return $cart_item_data;
}
// Optionally display Custom data in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'custom_data_on_cart_and_checkout', 99, 2 );
function custom_data_on_cart_and_checkout( $cart_data, $cart_item = null ) {
if( isset( $cart_item['custom_data']['custom_price'] ) )
$cart_data[] = array(
'name' => 'Custom price',
'value' => $cart_item['custom_data']['custom_price']
);
if( isset( $cart_item['custom_data']['custom_reference_meta'] ) )
$cart_data[] = array(
'name' => 'Custom reference',
'value' => $cart_item['custom_data']['custom_reference_meta']
);
return $cart_data;
}
代码进入功能。活动子主题(或活动主题)的php文件。
已测试并正常工作。