Display the weight of each cart items in WooCommerce

笑着哭i 提交于 2020-05-11 03:52:07

问题


I'm using Woocommerce and I'm trying to display the product weight for each product on cart page.

I have used this:

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>';
}

It display the total cart weight. I would like to also show the weight of each item in the cart as well.

How to display the product weight of each item on cart page?

Thanks.


回答1:


There is multiple ways to do it. You can use the custom function hooked in woocommerce_get_item_data filter hook to display the product weight of each cart items:

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;
}

*The Code goes in function.php file of your active child theme (or active theme). Tested and works.

To get the total line item weight (product weight x product quantity) replace:

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

by:

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

Reference: Class WC_Product::get_weight()



来源:https://stackoverflow.com/questions/42768375/display-the-weight-of-each-cart-items-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!