【发布时间】:2021-05-05 00:56:59
【问题描述】:
我 WooCommerce 我想显示购物车中商品的长度。
如何在 WooCommerce 中显示购物车商品的长度?
也许有一个短代码?
【问题讨论】:
-
嘿,我期待一些关于下面答案的反馈。
标签: php wordpress woocommerce cart variable-length
我 WooCommerce 我想显示购物车中商品的长度。
如何在 WooCommerce 中显示购物车商品的长度?
也许有一个短代码?
【问题讨论】:
标签: php wordpress woocommerce cart variable-length
要在购物车商品上显示产品长度,请使用WC_Product get_length() 方法,如下所示:
add_filter( 'woocommerce_get_item_data', 'display_cart_item_length', 20, 2 );
function display_cart_item_length( $cart_data, $cart_item ) {
$product_length = $cart_item['data']->get_length();
if( ! empty($product_length) ){
$cart_data[] = array(
'name' => __( 'Length', 'woocommerce' ),
'value' => wc_format_localized_decimal($product_length) . ' ' . get_option( 'woocommerce_dimension_unit' )
);
}
return $cart_data;
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。
或者,如果您想获取商品总长度并将其显示在购物车和结帐使用中;
// Shortcode to get cart items total length formatted for display
add_shortcode( 'items_total_length', 'wc_get_cart_items_total_length' );
function wc_get_cart_items_total_length(){
$total_length = 0; // Initializing variable
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
$product_length = $cart_item['data']->get_length(); // Get producct length
if( ! empty($product_length) ){
$total_length += $product_length * $cart_item['quantity']; // Sum item length x quantity
}
}
return wc_format_localized_decimal($total_length) . ' ' . get_option( 'woocommerce_dimension_unit' );
}
// Display total length in cart and checkout
add_action( 'woocommerce_cart_totals_before_order_total', 'display_cart_total_length' );
add_action( 'woocommerce_review_order_before_order_total', 'display_cart_total_length' );
function display_cart_total_length() {
echo '<tr class="length-total">
<th>' . esc_html__( 'Length', 'woocommerce' ) . '</th>
<td>' . do_shortcode("[items_total_length]") . '</td>
</tr>';
}
代码位于活动子主题(或活动主题)的functions.php 文件中。测试和工作
【讨论】: