在 Woocommerce 购物车页面中的购物车商品名称后添加产品 ID

Add the product ID after the cart item name in Woocommerce cart page

我想连接到 woocommerce 中的 'woocommerce_cart_item_name' 过滤器,并希望在名称后显示产品 ID。到目前为止我正在处理这个...

add_filter( 'woocommerce_cart_item_name', 'justatest' );

function justatest( $productname ) {
    echo $productname;
    // ideally echo name and product id here instead
}

这个 return 周围有 link 的名称,但我想在项目名称后添加产品的实际 ID。

如何在 Woocommerce 购物车页面中的购物车商品名称后添加产品 ID?

我知道我不需要先 return 因为那样会使我退出该功能,但我很好奇我将如何着手这样做。

试试这个,

覆盖以下woocommerce页面模板,

woocommerce/cart/cart.php in your theme

你会在里面找到tableHTML/code

<td class="product-name" data-title="<?php esc_attr_e('Product', 'woocommerce'); ?>"
<?php
if (!$product_permalink) {
   echo apply_filters('woocommerce_cart_item_name', $_product->get_name(). $product_id, $cart_item, $cart_item_key) . '&nbsp;';
} else {
   echo apply_filters('woocommerce_cart_item_name', sprintf('<a href="%s">%s</a>', esc_url($product_permalink), $_product->get_name() . $product_id), $cart_item, $cart_item_key);
}

// Meta data
echo WC()->cart->get_item_data($cart_item);

// Backorder notification
if ($_product->backorders_require_notification() && $_product->is_on_backorder($cart_item['quantity'])) {
   echo '<p class="backorder_notification">' . esc_html__('Available on backorder', 'woocommerce') . '</p>';
}
?>
</td>

将此部分添加到 cart.php

<td class="product-name">...</td>

希望对您有所帮助。

您的挂钩函数中缺少一些参数,您需要进行一些更改才能以这种方式获取产品 ID:

add_filter( 'woocommerce_cart_item_name', 'just_a_test', 10, 3 );
function just_a_test( $item_name,  $cart_item,  $cart_item_key ) {
    // Display name and product id here instead
    echo $item_name.' ('.$cart_item['product_id'].')';
}

此代码位于您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

已测试并有效。