我希望在购物车(产品栏下)和结账页面上显示SKU。
我在SO上搜索过,但所有答案都是针对旧版本的WooCommerce,而且没有一个是针对3.x的。
在WooCommerce 3中,如何在购物车和结账页面上显示SKU?
我在SO上搜索过,但所有答案都是针对旧版本的WooCommerce,而且没有一个是针对3.x的。
在WooCommerce 3中,如何在购物车和结账页面上显示SKU?
2021年更新
您可以通过在woocommerce_cart_item_name
动作钩子中挂接自定义函数来实现,方法如下:
// Display the sku below cart item name
add_filter( 'woocommerce_cart_item_name', 'display_sku_after_item_name', 5, 3 );
function display_sku_after_item_name( $item_name, $cart_item, $cart_item_key ) {
$product = $cart_item['data']; // The WC_Product Object
if( is_cart() && $product->get_sku() ) {
$item_name .= '<br><span class="item-sku">'. $product->get_sku() . '</span>';
}
return $item_name;
}
// Display the sku below under cart item name in checkout
add_filter( 'woocommerce_checkout_cart_item_quantity', 'display_sku_after_item_qty', 5, 3 );
function display_sku_after_item_qty( $item_quantity, $cart_item, $cart_item_key ) {
$product = $cart_item['data']; // The WC_Product Object
if( $product->get_sku() ) {
$item_quantity .= '<br><span class="item-sku">'. $product->get_sku() . '</span>';
}
return $item_quantity;
}
将代码放在您的活动子主题(或主题)的function.php文件中,也可以放在任何插件文件中。
此代码已经经过测试,并在WooCommerce 3+上运行。您将获得:
还有
您需要进行一些模板覆盖。
购物车
如果my_theme/woocommerce/cart/cart.php
中不存在,那么请将plugins/woocommerce/templates/cart/cart.php
复制到您的主题文件中。然后在大约第85行处添加以下内容:
// Meta data
// (this is already in cart.php; look for it for where to place the next snippet)
echo WC()->cart->get_item_data( $cart_item );
// Add SKU below product name
if ( !empty($_product->get_sku()) ) { ?>
<div class="sku">
<small><?php echo "SKU: ". $_product->get_sku(); ?></small>
</div>
<?php }
结账
如果您的主题文件夹中没有 my_theme/woocommerce/checkout/review-order.php
这个文件,请将 plugins/woocommerce/templates/checkout/review-order.php
复制到该位置。然后在大约第43行添加以下内容:
<?php
// (this is already in review-order.php; look for it for where to place the next snippet)
echo WC()->cart->get_item_data( $cart_item ); ?>
<?php
// Add SKU below product name
if ( !empty($_product->get_sku()) ) { ?>
<div class="sku">
<small><?php echo "SKU: ". $_product->get_sku(); ?></small>
</div>
<?php } ?>
/**
* @snippet Show SKU @ WooCommerce Cart
* @author Khalid Almallahi
*/
add_action( 'woocommerce_after_cart_item_name', 'abukotsh_sku_below_cart_item_name', 11, 2 );
function abukotsh_sku_below_cart_item_name( $cart_item, $cart_item_key ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$sku = $_product->get_sku();
if ( ! $sku ) return;
echo '<p><small>SKU: ' . $sku . '</small></p>';
}