目前,没有直接的方法将自定义价格添加到通过函数添加的产品中$woocommerce->cart->add_to_cart
(Documentation) 但我们有一种绕过的方式,我在下面的代码中解释
global $woocommerce;
$custom_price = 1000;
// Cart item data to send & save in order
$cart_item_data = array(\'custom_price\' => $custom_price);
// woocommerce function to add product into cart check its documentation also
// what we need here is only $product_id & $cart_item_data other can be default.
$woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
// Calculate totals
$woocommerce->cart->calculate_totals();
// Save cart to session
$woocommerce->cart->set_session();
// Maybe set cart cookies
$woocommerce->cart->maybe_set_cart_cookies();
在函数文件中,可以放置以下代码
function woocommerce_custom_price_to_cart_item( $cart_object ) {
if( !WC()->session->__isset( "reload_checkout" )) {
foreach ( $cart_object->cart_contents as $key => $value ) {
if( isset( $value["custom_price"] ) ) {
//for woocommerce version lower than 3
//$value[\'data\']->price = $value["custom_price"];
//for woocommerce version +3
$value[\'data\']->set_price($value["custom_price"]);
}
}
}
}
add_action( \'woocommerce_before_calculate_totals\', \'woocommerce_custom_price_to_cart_item\', 99 );
你可以走了