在 woocommerce 网店中,我有特定的四个类别 类别_1、类别_2、类别_3 和类别_4 我想更改运费。 具体来说,当有人从前 3 个类别(category_1、category_2 和 category_3)中选择产品时,我想通过特定类别的产品更改运费。 当某人从 category_1 中选择商品时,购物成本将修改为 10,从 category_2 中,购物成本将修改为 10,从 category_3 中,购物成本将修改为 75。 但是当有人从最后一个类别(category_4)中选择产品时,运费必须由产品属性'size'修改。 属性“size”的值为“small”、“medium”和“large”。 具体来说,当有人选择“小”尺寸的产品时,运费为 38,“中”尺寸的运费为 50,“大”尺寸的运费为 62。
add_filter( 'woocommerce_package_rates', 'change_shipping_cost', 10, 2 ); 函数 change_shipping_cost( $rates, $package ) {
$shipping_method = 'flat_rate:11';
$categories = array( 'category_1', 'category_2', 'category_3', 'category_4' );
$max_quantity = 0;
foreach ( $package['contents'] as $item ) {
if ( has_term( $categories, 'product_cat', $item['product_id'] ) ) {
$max_quantity = max( $max_quantity, $item['quantity'] );
}
}
if ( isset( $rates[ $shipping_method ] ) ) {
if ( $max_quantity == 1 ) {
$max_cost = 0;
$petbed_category_cost = array(
'small' => 38,
'medium' => 50,
'large' => 62
);
foreach ( $package['contents'] as $item ) {
if ( has_term( $categories, 'product_cat', $item['product_id'] ) ) {
if ( has_term( 'category_1', 'product_cat', $item['product_id'] ) ) {
$max_cost = max( $max_cost, 10 );
}
if( has_term ( 'category_2', 'product_cat', $item['product_id']) ){
$max_cost = max( $max_cost, 10 );
}
if (has_term ('category_3', 'product_cat', $item['product_id'] ) ){
$max_cost = max( $max_cost, 75 );
}
if (has_term ('category_4', 'product_cat', $item['product_id'])){
$product = wc_get_product( $item['product_id'] );
if ( $product && $product->is_type( 'variable' ) ) {
$variation = wc_get_product( $item['variation_id'] );
if ( $variation ) {
$size = $variation->get_attribute('size');
if ( isset( $petbed_category_cost[ $size ] ) )
{
$max_cost = max( $max_cost, $petbed_category_cost[ $size ] );
}
}
} elseif ( $product ) {
$size = $product->get_attribute('size');
if ( isset( $petbed_category_cost[ $size ] ) ) {
$max_cost = max( $max_cost, $petbed_category_cost[ $size ] );
}
}
}
}
}
$rates[ $shipping_method ]->cost = $max_cost;
}
}
}
return $rates;
}
创建了上面的代码。当有人从前三个类别中选择产品时,运费就会发生变化。但是当从 category_4 中选择具有特定属性(例如“medium”)的产品时,运费不会在 eshop 中显示。 我怎么解决这个问题? 提前谢谢你!