php - 根据尺寸计算自定义 Woocommerce 产品重量

标签 php wordpress woocommerce attributes product

将产品添加到我的 woocommerce 商店时,我设置了重量(以千克为单位)和尺寸(以厘米为单位)。如果 [(高度 x 长度 x 宽度)/5000] 高于实际重量,那么我希望用它来计算运费。

我以为我可以使用过滤器来操纵 $weight 但没有成功。这是我的代码:

function woocommerce_product_get_weight_from_dimensions( $weight ) {
    global $product;
    $product = wc_get_product( id );
    $prlength = $product->get_length();
    $prwidth = $product->get_width();
    $prheight = $product->get_height();
    $dimensions = $prlength * $prwidth * $prheight;
    $dweight = $dimensions / 5000;
    if ($dweight > $weight) {
        return $dweight;
    }
    return $weight;
}
add_filter('woocommerce_product_get_weight', 'woocommerce_product_get_weight_from_dimensions');

我做错了什么?

最佳答案

$product = wc_get_product( id ); 存在错误,因为 id 应该是像 $id 一样定义的变量 相反。

此外,WC_Product 对象已经是您的 Hook 函数中缺少的可用参数。

最后,我重新审视了您的代码,使其更加紧凑:

add_filter( 'woocommerce_product_get_weight', 'custom_get_weight_from_dimensions', 10, 2 );
function custom_get_weight_from_dimensions( $weight, $product ) {
    $dim_weight = $product->get_length() * $product->get_width() * $product->get_height() / 5000;
    return $dim_weight > $weight ? $dim_weight : $weight;
}

代码位于事件子主题(或主题)的 function.php 文件中或任何插件文件中。

此代码经过测试并且可以工作。

关于php - 根据尺寸计算自定义 Woocommerce 产品重量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46768483/

相关文章:

javascript - 搜索产品无法在 "New order"中运行(Woocommerce)

wordpress - 重新排序 Woocommerce 结帐字段

php - 重力表格获取字段条目

php - Laravel max_prepared_stmt_count 错误

php - yii 和 jquery 移动

php - 如果产品来自某个类别,则 WooCommerce 执行功能

javascript - Woocommerce 3 中没有在线支付交易的订单的谷歌分析集成

php - 使用 MySQL 数据库字段枚举值填充 PHP 组合框

jquery - 如何使用jquery获取wordpress中的当前页面id

javascript - 如何让我的自定义 UI 组件与我的自定义 Wordpress 主题正确配合?