php - 增加 WooCommerce 购物车中每个类别计数的运费
问题描述
我正在尝试根据购物车中的类别数量(计数)增加运费。到目前为止,我有这个:
add_filter( 'woocommerce_package_rates', 'vh_wc_shipping_costs', 20 );
function vh_wc_shipping_costs( $rates ) {
$increase_cost = 50;
$cat_ids = array();
$count = 0;
foreach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {
$cat_ids = array_merge(
$cat_ids,
(array) $cart_item['data']->get_category_ids()
);
$count = count( $cat_ids );
}
$i=0;
if ( $count >= 1 ) {
foreach ( $rates as $rate_key => $rate ) {
$i++; $i <= $count;
// Excluding free shipping methods
if ( 'free_shipping' !== $rate->method_id ) {
// Get old cost
$old_cost = $rates[ $rate_key ]->cost;
// Set rate cost
$rates[ $rate_key ]->cost = $old_cost + $increase_cost;
}
}
}
return $rates;
}
但由于某种原因,它不会增加每个额外类别的运费。另外,我想在额外费用中添加注释。任何建议表示赞赏。
解决方案
由于 StackOverFlow 的规则当时是一个问题,我将只回答与您的代码相关的第一个问题。
以下代码将为购物车中的每个其他产品类别添加额外的运费(所以不是第一个):
add_filter( 'woocommerce_package_rates', 'filter_shipping_rates_costs', 10, 2 );
function filter_shipping_rates_costs( $rates, $package ) {
$step_cost = 50;
$term_ids = array();
// Loop through cart items for the current shipping package
foreach( $package['contents'] as $cart_item ){
$term_ids = array_merge(
$term_ids,
(array) $cart_item['data']->get_category_ids()
);
}
$terms_count = count( $term_ids );
// Loop through shipping rates
foreach ( $rates as $rate_key => $rate ) {
// Excluding free shipping methods
if ( 'free_shipping' !== $rate->method_id && $terms_count > 1 ) {
// Set rate cost
$rates[$rate_key]->cost = $rate->cost + ($step_cost * ($terms_count - 1));
}
}
return $rates;
}
现在,如果您想为购物车中的每个类别添加额外的运费,请使用以下命令:
add_filter( 'woocommerce_package_rates', 'filter_shipping_rates_costs', 10, 2 );
function filter_shipping_rates_costs( $rates, $package ) {
$step_cost = 50;
$term_ids = array();
// Loop through cart items for the current shipping package
foreach( $package['contents'] as $cart_item ){
$term_ids = array_merge(
$term_ids,
(array) $cart_item['data']->get_category_ids()
);
}
$terms_count = count( $term_ids );
// Loop through shipping rates
foreach ( $rates as $rate_key => $rate ) {
// Excluding free shipping methods
if ( 'free_shipping' !== $rate->method_id && $terms_count > 0 ) {
// Set rate cost
$rates[$rate_key]->cost = $rate->cost + ($step_cost * $terms_count);
}
}
return $rates;
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。测试和工作。
刷新运输缓存:
- 此代码已保存在您的 functions.php 文件中。
- 在运输区域设置中,禁用/保存任何运输方式,然后启用返回/保存。
你已经完成了,你可以测试它。
推荐阅读
- node.js - NodeJS - 内存不足
- javascript - 有没有办法改变点击事件的函数名?
- sql - SQL 连接和计算行数(计算表中的人)
- mysql - 如何在 che.openshift.io 上托管的 eclipse che 上使用数据库获取持久工作区
- mongodb - MongoDB中的项目字段,我不知道中间字段名称
- git - 为什么我删除了冲突文件,但仍然无法从远程 git pull?
- spring - 使用 JooQ 获取一对多关联
- python - 如何在 Pymc3 中定义瑞利先验?
- javascript - 对于每个触发器,如何在其触发器上动态显示 bootstrap-5 模态位置
- robotframework - 带有额外 / 的 HTTPSConnectionPool