【发布时间】:2020-08-20 00:05:26
【问题描述】:
在 Storefront 主题中,我使用下面的代码将格式化的重量从 1000g 更改为 1kg:
add_action('woocommerce_after_shop_loop_item_title', 'show_weight', 10);
function show_weight()
{
global $product;
$attributes = $product->get_attributes();
if ($product->has_weight()) {
$weight = $product->get_weight();
$weight_unit = 'grams';
if ($weight >= 1000) {
$weight = round(($weight / 1000), 2);
$weight_unit = 'kg';
}
print '<p>Weight: ' . $weight . ' ' . $weight_unit . '</p>';
}
}
如何在中显示相同的格式
- 购物车和结帐页面
- 订单和电子邮件
以下代码最初取自 "Display the weight of cart and order items in WooCommerce" 回答线程,我已被建议在此处作为新问题发布。
我需要下面的代码从重量格式化
- 1000g以上到1kg
- 和 500 克一样。
// 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' ), ( $cart_item['quantity'] * $cart_item['data']->get_weight() ) . ' ' . get_option('woocommerce_weight_unit') );
}
}
【问题讨论】:
标签: php wordpress woocommerce attributes hook-woocommerce