我试图让WooCommerce购物车计算将运费乘以购物车中不同自定义分类术语的数量。
例如,我的自定义分类法名称/slug是'city'。如果存在3个不同的产品分类术语(例如:波士顿,华盛顿和纽约),当前的运货率应乘以3。
这是我当前的代码:
add_filter( 'woocommerce_package_rates', 'funkcija');
function funkcija ( $rates ) {
$cart = WC()->cart;
// here I define the array where custom taxonomies will be saved in the foreach loop
$mojarray = array();
// the foreach loop that iterates through cart items and saves every taxonomy term in the array
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
$terms = wp_get_post_terms( $product_id, 'city' );
$mojarray[] = $terms;
}
//now here the counter is defined, the array is set to contain only unique values of the taxonomies
$counter = 0;
$noviarray = array_unique($mojarray);
foreach ($noviarray as $value) {
// for each unique taxonomy present in cart, increase the counter by 1
++$counter;
}
//here the rates totals are taken and multiplied with $counter
foreach($rates as $key => $rate ) {
$currenttotal = $rates[$key]->cost;
$multipliedtotal = $currenttotal * $counter;
$rates[$key]->cost = $multipliedtotal;
}
return $rates;
}
不幸的是,这段代码将购物车中每个产品的价格相乘。我已经多次浏览了代码,但不明白为什么它不能像预期的那样用于唯一分类法术语。
我相信这是可测试的任何WooCommerce商店与任何自定义分类法。任何建议吗?
你的代码中有一些错误
-
不需要使用
WC()->cart
,因为woocommerce_package_rates
钩子包含不是1个而是2个参数,从第二个,即$package
,您可以获得必要的信息 -
wp_get_post_terms()包含第三个参数,即
$args
,因此添加了array( 'fields' => 'names' )
-
由于您目前将此应用于所有
$rates
,我在我的答案中添加了一个if条件,您可以指定1个或多个方法。如果你不想这样,你可以删除If条件
得到:
function filter_woocommerce_package_rates( $rates, $package ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return $rates;
// Initialize
$counter = 0;
$my_array = array();
// Loop through line items
foreach ( $package['contents'] as $line_item ) {
// Get product id
$product_id = $line_item['product_id'];
// Get terms
$term_names = wp_get_post_terms( $product_id, 'city', array( 'fields' => 'names' ) );
// Loop through (unique values)
foreach ( $term_names as $term_name ) {
// Checks if a value NOT exists in an array
if ( ! in_array( $term_name, $my_array, true ) ) {
// Push one or more elements onto the end of array
array_push( $my_array, $term_name );
}
}
}
// Counts all elements in an array
$counter = count( $my_array );
// Greater than
if ( $counter > 0 ) {
// Loop through rates
foreach ( $rates as $rate_key => $rate ) {
// Target specific methods, multiple can be added, separated by a comma
if ( in_array( $rate->method_id, array( 'flat_rate', 'table_rate' ) ) ) {
// Get rate cost
$cost = $rates[$rate_key]->cost;
// Greater than
if ( $cost > 0 ) {
// Set rate cost
$rates[$rate_key]->cost = $cost * $counter;
}
}
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );