我正在尝试创建一个表单,该表单允许用户输入自定义捐赠金额并自动更改产品价格。我需要“产品”之外的表格,该表格最终将允许用户使用收音机选择3种产品之一。为了我的一生,我无法将表单输入传递到购物车。
到目前为止,这是我想要的,只是尝试使其在单个产品上运行:
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="add-to-cart" value="11">
<input type="text" name="donation">
<button type="submit">Add Donation</button>
</form>
和一些功能:
// Sanitize Data
function donation_add_cart_item_data( $cart_item, $product_id ){
if( isset( $_POST['donation'] ) ) {
$cart_item['donation'] = sanitize_text_field( $_POST['donation'] );
}
return $cart_item;
}
add_filter( 'woocommerce_add_cart_item_data', 'donation_add_cart_item_data', 10, 2 );
// Add Data to Cart Item
function donation_get_cart_item_from_session( $cart_item, $values ) {
if ( isset( $values['donation'] ) ){
$cart_item['donation'] = $values['donation'];
}
return $cart_item;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'donation_get_cart_item_from_session', 20, 2 );
Set Custom Price for Donations Based on Form Input
function woo_add_donation( $cart_object, $values=null ) {
if( isset( $values['donation']) ){
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->price = $values['donation'];
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'woo_add_donation');
必须有一种更简单的方法,这是行不通的。该产品的最终价格为0。
答案 0 :(得分:0)
我在这里找到了答案:Change cart item price based on custom cart data in WooCommerce
我能够根据自己的目的进行调整:
add_filter( 'woocommerce_add_cart_item', 'add_custom_cart_item_data', 10, 2 );
function add_custom_cart_item_data( $cart_item_data, $cart_item_key ) {
if( isset( $_POST['donation'] ) )
$cart_item_data['donation'] = $_POST['donation'];
return $cart_item_data;
}
add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_price', 10, 1 );
function set_custom_cart_item_price( $wc_cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// First loop to check if product 11 is in cart
foreach ( $wc_cart->get_cart() as $cart_item ){
if( ! empty($cart_item['donation']) )
$cart_item['data']->set_price( $cart_item['donation'] );
}
}
像魅力一样工作!