需要挂钩才能在购物车页面中输入

时间:2020-02-29 04:21:55

标签: php wordpress woocommerce hook-woocommerce

我试图更改购物车页面上的产品价格,并进一步根据用户在购物车部分的购物车页面上输入元素输入的一个参数作为购物车表的另一字段。

在此处cart.php

echo '<label></label><input name="'.apply_filters( 'woocommerce_cart_item_product', sprintf( $cart_item_key ), $cart_item, $cart_item_key ).'" value="%s" type="number" min="0" max="100"/>';

我不知道该如何应用这些钩子,就像我在插件中单个产品页面上所做的那样,从这些输入中检索数据,因为价格将在所有元数据,购物车页面抵押品等方面发生变化。

这是插件文件

<?php 
/**
 * Plugin Name: piwpow
 * Description: guntogetout
 * Plugin URI: http://#
 * Author: that genius
 */
// Display custom input fields in single product page
add_action( 'woocommerce_before_add_to_cart_button', 'add_product_custom_fields', 20 );
function add_product_custom_fields(){
    $domain =  'woocommerce';
    $value = isset( $_POST['amount_of_thanks'] ) ? sanitize_key( $_POST['amount_of_thanks'] ) : '';
    printf( '<label>%s</label><input name="amount_of_thanks" value="%s" type="number" min="0" max="100"/><br>', __( 'Luck', $domain ), esc_attr( $value ) );
}   

// Add custom fields data to cart items and make calculation price
add_filter( 'woocommerce_add_cart_item_data', 'custom_add_cart_item_data', 20, 3 );
function custom_add_cart_item_data(  $cart_item, $product_id, $cart_item_key  ){

    if( isset( $_POST['amount_of_thanks'] ) ) {
        $cart_item['custom_data']['thanks'] = sanitize_key( $_POST['amount_of_thanks'] );
    }

    if( isset( $_POST['amount_of_thanks'] ) ) {
        $thanks  = (int) sanitize_key( $_POST['amount_of_thanks'] );
    }

    $product = wc_get_product( $product_id );

    $price = $product->get_price();

        if( $thanks > 0 ){

            $total_price = $price+($price*$thanks)/100; 
            $cart_item['custom_data']['price'] = round($total_price, 2); 

    return $cart_item;
}
}
// Set the new calculated price replacing cart item price
add_action( 'woocommerce_before_calculate_totals', 'set_cart_item_calculated_price', 20, 1 );
function set_cart_item_calculated_price( $cart_item ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( wc()->cart->get_cart() as $cart_item ){
        if( ! isset( $cart_item['custom_data']['price'] ) ){
            continue;
        }
        if( $cart_item['custom_data']['price'] > 0 ){
            // Set the calculated item price (if there is one)
            $cart_item['data']->set_price( (float) $cart_item['custom_data']['price'] );
    }
}
}
?>

或者也许还有其他建议

0 个答案:

没有答案