在WooCommerce中显示每个购物车项目的重量

时间:2017-03-13 16:12:33

标签: php wordpress woocommerce cart hook-woocommerce

我正在使用Woocommerce,我正试图在购物车页面上显示每种产品的产品重量。

我用过这个:

add_action('woocommerce_cart_collaterals', 'myprefix_cart_extra_info');
function myprefix_cart_extra_info() {
    global $woocommerce;
    echo '<div class="cart-extra-info">';
    echo '<p class="total-weight">' . __('Total Weight:', 'woocommerce');
    echo ' ' . $woocommerce->cart->cart_contents_weight . ' ' . get_option('woocommerce_weight_unit');
    echo '</p>';
    echo '</div>';
}

显示购物车总重量。我还想显示购物车中每件商品的重量。

如何在购物车页面上显示每件商品的产品重量?

感谢。

1 个答案:

答案 0 :(得分:1)

有多种方法可以做到这一点。您可以使用隐藏在 woocommerce_get_item_data 过滤器挂钩中的自定义功能来显示每个购物车项目的产品重量:

add_filter( 'woocommerce_get_item_data', 'displaying_cart_items_weight', 10, 2 );
function displaying_cart_items_weight( $item_data, $cart_item ) {
    $item_weight = $cart_item['data']->get_weight();
    $item_data[] = array(
        'key'       => __('Weight', 'woocommerce'),
        'value'     => $item_weight,
        'display'   => $item_weight . ' ' . get_option('woocommerce_weight_unit')
    );

    return $item_data;
}

*代码位于您的活动子主题(或活动主题)的function.php文件中。经过测试和工作。

获取总订单项重量(产品重量x产品数量)替换:

$item_weight = $cart_item['data']->get_weight();

由:

$item_weight = $cart_item['data']->get_weight() * $product_qty;

参考:Class WC_Product::get_weight()