我試圖讓 WooCommerce 購物車計算將運費乘以購物車中不同自定義分類術語的數量。
例如,我的自定義分類名稱/slug 是“城市”。如果存在 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 商店上進行測驗。有什么建議嗎?
uj5u.com熱心網友回復:
您的代碼包含一些錯誤
使用的
WC()->cart是沒有必要的,因為woocommerce_package_rates鉤不包含1,但2個引數,并從2日,也就是$package你可以得到必要的資訊wp_get_post_terms()包含第三個引數,即
$args,所以array( 'fields' => 'names' )已添加由于您目前將此應用于 all
$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 );
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/328783.html
標籤:WordPress的 求购 大车 运输 自定义分类法
上一篇:Woocommerce-當產品處于缺貨狀態時禁用add_to_cart按鈕
下一篇:根據資料庫可用性顯示方面
