我使用WooCommerce Per Product Shipping插件根据产品设置运费,然而,这个插件没有提供任何内置功能,只收取整个订单最昂贵的运费,就像核心的WooCommerce统一运费允许您设置计算类型一样.
我只收取最高运费的运费.我承认我使用人工智能生成了这段代码(因为我不是开发人员),我try 了几种方法来实现它,但我一直收到一个严重错误:
/**
* Retrieve shipping costs for a WooCommerce product.
*
* @param int $product_id The ID of the WooCommerce product.
* @return float|null Shipping cost for the product, or null if not found.
*/
function get_shipping_cost_for_product( $product_id ) {
$shipping_methods = WC()->shipping->get_packages();
foreach ( $shipping_methods as $package ) {
foreach ( $package['rates'] as $rate ) {
// Check if the shipping rate is applicable to the product.
if ( $rate->method_id === '11' && $rate->get_instance_id() === 0 ) {
// Retrieve the shipping cost for the product.
return $rate->cost;
}
}
}
return null; // Shipping cost not found.
}
/**
* Custom function to calculate shipping costs for WooCommerce Per Product Shipping.
*
* @param array $package Shipping package.
* @return void
*/
function custom_per_product_shipping_cost( $package ) {
if ( ! is_array( $package['contents'] ) ) {
return;
}
// Initialize variables to keep track of the highest shipping cost.
$highest_shipping_cost = 0;
// Loop through each item in the cart.
foreach ( $package['contents'] as $item_id => $item ) {
$product_id = $item['product_id'];
// Get the shipping cost for the current product.
$shipping_cost = get_shipping_cost_for_product( $product_id );
// Compare with the highest shipping cost found so far.
if ( $shipping_cost > $highest_shipping_cost ) {
$highest_shipping_cost = $shipping_cost;
}
}
// Set the calculated highest shipping cost for the entire order.
$package['contents_cost'] = $highest_shipping_cost;
// Update the package shipping costs.
WC()->cart->shipping_total = $highest_shipping_cost;
WC()->cart->shipping_tax_total = 0; // You may need to adjust tax calculation.
WC()->cart->shipping_taxes = array();
WC()->cart->shipping_methods = array();
// Recalculate cart totals.
WC()->cart->calculate_totals();
}
// Hook into the shipping calculation process.
add_action( 'woocommerce_cart_shipping_packages', 'custom_per_product_shipping_cost' );
任何帮助都将不胜感激.
Per Product Shipping settings. Tax status: taxable; nothing set for Default Product Cost, Handling Fee per product or per order, and nothing checked with regard to ignoring other methods. See screenshot.
未启用其他发货方式
On a product, I have enabled per product shipping and have added three rows (Us, HI, AK) with an item cost. See screenshot