WooCommerce 购物车费用根据自定义产品输入字段计算

WooCommerce cart Fee calculated from Custom products input field

我像这样向产品添加了一个输入元素:

add_action( 'woocommerce_before_add_to_cart_button', 'add_tip_input', 9 );

function add_tip_input() {
    if (is_single(1272)){
    $value = isset( $_POST['custom_tip_add_on']);
    echo '<div><label class="pour_boire" title="votre appréciation">Votre appréciation</label><p><input type="number" step="1" min="0" name="custom_tip_add_on" value="' . $value . '"></p></div>';
    }
}

这很好用。现在我尝试将此值添加到购物车并更新总数。为此,我使用 woocommerce_cart_calculate_fees 钩子:

add_action( 'woocommerce_cart_calculate_fees', 'add_tip', 20, 1 );

function add_tip( $cart ) {
   if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
   $value = WC()->session->get( 'custom_tip_add_on' );
   $cart->add_fee( 'Votre appréciation', $value );
}

这将向购物车添加新行,但值为 0,00! 显然,这是错误的方式。当我用正数替换 $value 时,一切正常。 但是我尝试将输入字段的值传递给 $value,但我失败了。

非常感谢任何帮助。

在这种情况下不需要使用 WC_sessions。相反,您需要将此自定义产品字段添加为自定义购物车项目数据:

add_action( 'woocommerce_before_add_to_cart_button', 'add_product_tip_input_field', 9 );
function add_product_tip_input_field() {
    // Targeting specific product (or post)
    if (is_single(1272)){
        $title = __("Votre appréciation", "woocommerce");

        printf( 
            '<div class="custom-tip-wrapper">
                <label for="custom_tip" class="pour_boire" title="%s">%s</label>
                <p><input type="number" step="1" min="0" name="custom_tip" value="%s"></p>
            </div>',
            $title, $title, isset($_POST['custom_tip']) ? (int) $_POST['custom_tip'] : '0'
        );
    }
}

// Add the tip as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'filter_add_cart_item_data_callback', 10, 3 );
function filter_add_cart_item_data_callback( $cart_item_data, $product_id, $variation_id ) {
    if ( isset( $_POST['custom_tip'] ) &&  $_POST['custom_tip'] > 0 ) {
        $cart_item_data['custom_tip'] = (int) wc_clean( $_POST['custom_tip'] );
        $cart_item_data['unique_key'] = md5( microtime().rand() ); // Make each item unique
    }
    return $cart_item_data;
}

add_action( 'woocommerce_cart_calculate_fees', 'wc_tips_fee', 20, 1 );
function wc_tips_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    $fee = 0; // Initializing variable

    // Loop through cart items and get the tips from each item
    foreach ( $cart->get_cart() as $cart_item ) {
        if ( isset($cart_item['custom_tip']) ) {
            $fee += $cart_item['custom_tip'];
        }

    }

    if( $fee > 0 ) {
        $cart->add_fee( __("Votre appréciation", "woocommerce"), $fee );
    }
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。