在Woocommerce 3中在购物车和结账页面上显示SKU

5
我希望在购物车(产品栏下)和结账页面上显示SKU。
我在SO上搜索过,但所有答案都是针对旧版本的WooCommerce,而且没有一个是针对3.x的。
在WooCommerce 3中,如何在购物车和结账页面上显示SKU?
3个回答

10

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

enter image description here

还有

enter image description here

相关类似: 如何在订单接收页面和电子邮件订单中显示SKU与产品标题


谢谢你的回答。 我已经将代码添加到我的活动主题functions.php文件中,但SKU仍然没有显示。 我的产品是可变产品,所有变量都有不同的SKU,但我想这应该并不重要。还有其他提示吗? - Vedran Janjic
2
非常简单。谢谢! - MarkPraschan
刚刚尝试了一下WooCommerce 6.3.1,完美运行! - sacredfaith

2

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

购物车

如果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 } ?>

我已经尝试过了,SKU没有显示。谢谢您的回答! - Vedran Janjic

0
你可以用以下方式实现:
/**
 * @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>';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接