Display the weight of cart and order items in WooCommerce

元气小坏坏 提交于 2020-05-26 08:03:53

问题


How can I to put the weight of each item under your description on the cart page and the payment page in woocommerce?

Any advice is welcome.


回答1:


2020 Updated

The following code will display the subtotal item weight for cart and order items everywhere:

// Display the cart item weight in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'display_custom_item_data', 10, 2 );
function display_custom_item_data( $cart_item_data, $cart_item ) {
    if ( $cart_item['data']->get_weight() > 0 ){
        $cart_item_data[] = array(
            'name' => __( 'Weight subtotal', 'woocommerce' ),
            'value' =>  ( $cart_item['quantity'] * $cart_item['data']->get_weight() )  . ' ' . get_option('woocommerce_weight_unit')
        );
    }
    return $cart_item_data;
}

// Save and Display the order item weight (everywhere)
add_action( 'woocommerce_checkout_create_order_line_item', 'display_order_item_data', 20, 4 );
function display_order_item_data( $item, $cart_item_key, $values, $order ) {
    if ( $values['data']->get_weight() > 0 ){
        $item->update_meta_data( __( 'Weight subtotal', 'woocommerce' ), ( $values['quantity'] * $values['data']->get_weight() )  . ' ' . get_option('woocommerce_weight_unit') );
    }
}

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


If you want to display the product weight instead, in cart and order items you will use:

// Display the cart item weight in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'display_custom_item_data', 10, 2 );
function display_custom_item_data( $cart_item_data, $cart_item ) {
    if ( $cart_item['data']->get_weight() > 0 ){
        $cart_item_data[] = array(
            'name' => __( 'Weight', 'woocommerce' ),
            'value' =>  $cart_item['data']->get_weight()  . ' ' . get_option('woocommerce_weight_unit')
        );
    }
    return $cart_item_data;
}

// Save and Display the order item weight (everywhere)
add_action( 'woocommerce_checkout_create_order_line_item', 'display_order_item_data', 20, 4 );
function display_order_item_data( $item, $cart_item_key, $values, $order ) {
    if ( $values['data']->get_weight() > 0 ){
        $item->update_meta_data( __( 'Weight', 'woocommerce' ), $values['data']->get_weight()  . ' ' . get_option('woocommerce_weight_unit') );
    }
}

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




回答2:


go to directory wp-content\plugins\woocommerce\templates\cart and add code there

 <tr>
         <th>Total Weight</th>
        <td><?php echo WC()->cart->cart_contents_weight . ' ' . get_option('woocommerce_weight_unit'); ?></td>
        </tr>


来源:https://stackoverflow.com/questions/51851028/display-the-weight-of-cart-and-order-items-in-woocommerce

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