Woocommerce:根据价格、成本和税率计算,将每个产品的税费设置为不同的自定义值

Len*_*ena 9 php wordpress woocommerce

我正在尝试为 Woocommerce 中的每个产品设置自定义税值,其计算如下:

(price - cost) * (0,19/1,19)
Run Code Online (Sandbox Code Playgroud)

由于 Woocommerce 不提供产品成本字段,因此我安装了商品成本 - Woocommerce扩展,该扩展允许将此信息添加到每个产品中。

然后我继续寻找计算税收的函数(calc_tax( $price, $rates, $price_includes_tax = false, $deprecated = false),并找到了挂钩“woocommerce_calc_tax”,我想我必须挂钩才能更改计算的税收:

apply_filters( 
  'woocommerce_calc_tax',  
  $taxes,  
  $price,  
  $rates,  
  $price_includes_tax,  
  $suppress_rounding 
);  
Run Code Online (Sandbox Code Playgroud)

文件中[includes/class-wc-tax.php][2]

但由于该钩子仅提供五个参数 - 其中没有一个代表产品的成本。我不知道如何将产品的成本传递给挂钩该挂​​钩的函数。

所以我的问题是,如何将产品成本(从商品成本插件)传递到此挂钩以用于如上所述的自定义税计算。

或者有其他方法可以做到这一点吗?

Yas*_*ash 0

<?php
// Display product's custom tax with product in cart and checkout, not added in product's price
// Remove, if not show this to user
function display_custom_tax_with_product_on_cart_and_checkout( $item_data, $cart_item ) {
    $item = $cart_item['data'];
    $product_id = $item->get_id();
    $product_price = $item->get_price();
    
    // Do some magic here to get the cost of the product (use $product_id).
    $cost_of_product = $Get_Cost_Of_Product;

    if ( is_numeric( $cost_of_product ) ) {
        $custom_tax = round( ( $product_price - $cost_of_product ) * ( 0.19 / 1.19 ), 2 );
        $item_data[] = array(
            'name'  => __( 'Custom Tax on this is', 'woocommerce' ),
            'value' => $custom_tax,
        );
    }
    return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'display_custom_tax_with_product_on_cart_and_checkout', 10, 2 );

// Get all product's total custom Tax and add that at total calculation
// this create field name "Total Custom Tax:" at cart and checkout
function add_custom_tax() {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return;
    }

    $custom_tax = 0;

    foreach ( WC()->cart->get_cart() as $values ) {
        $item = $values['data'];
        if ( empty( $item ) ) {
            break;
        }

        $product_id = $item->get_id();
        $product_price = $item->get_price();

        // Do some magic here to get the cost of the product (use $product_id).
        $cost_of_product = $Get_Cost_Of_Product;

        if ( is_numeric( $cost_of_product ) ) {
            $custom_tax += round( ( $product_price - $cost_of_product ) * ( 0.19 / 1.19 ), 2 );
        }
    }

    if ( $custom_tax > 0 ) {
        WC()->cart->add_fee( 'Total Custom Tax:', $custom_tax, false );
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'add_custom_tax' );
Run Code Online (Sandbox Code Playgroud)

下面我添加了购物车页面的图像,以便更好地理解我的答案

这是这些自定义税码之后的购物车页面


如果这不适合任何人,那么ntk4的评论也建议了更好的方法!