在 Woocommerce 3 的购物车和结帐页面上显示 SKU

Show SKU on cart and checkout pages in Woocommerce 3

我想在购物车(在产品栏下)和结帐页面上显示 SKU。

我搜索了 SO,但所有答案都是针对旧版本的 WooCommerce,没有一个是针对 3.x。

如何在 Woocommerce 3 的购物车和结账页面上显示 SKU?

您需要进行一些模板覆盖。

购物车

plugins/woocommerce/templates/cart/cart.php 复制到位于 my_theme/woocommerce/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 }

结账

plugins/woocommerce/templates/checkout/review-order.php 复制到位于 my_theme/woocommerce/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 } ?>

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+。您将获得:

相关相似:

你可以这样操作:

/**
 * @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>';
}