php - 在特定产品的 WooCommerce 购物车页面中的购物车项目名称后添加产品 ID

标签 php wordpress woocommerce product cart

我希望连接到 WooCommerce 中的 woocommerce_cart_item_name 过滤器,并希望仅在特定产品的名称后显示产品 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'].')';
}

这确实会返回带有产品 ID 的名称,但它适用于我商店中的所有产品。

只想显示指定产品的产品 ID。我很好奇我会怎么做?

最佳答案

jpneey 给出的答案不起作用(HTTP 错误 500),因为:

  • echo 被用来代替 return

所以你得到:

function filter_woocommerce_cart_item_name( $item_name, $cart_item, $cart_item_key ) {
    // The targeted product ids, multiple product IDs can be entered, separated by a comma
    $targeted_ids = array( 30, 815 );
    
    // Product ID
    $product_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];
    
    if ( in_array( $product_id, $targeted_ids ) ) {
        return $item_name . ' (' . $product_id . ')';
    }

    return $item_name;
}
add_filter( 'woocommerce_cart_item_name', 'filter_woocommerce_cart_item_name', 10, 3 );

关于php - 在特定产品的 WooCommerce 购物车页面中的购物车项目名称后添加产品 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67595163/

相关文章:

javascript - 在 WooCommerce 的 jQuery 日期选择器问题中禁用工作日和假期

php - 如何使用像 gulp.js 这样的构建系统和像 Bower 这样的依赖管理器

php - Composer 下载私有(private) GitHub 存储库

php - MySql 中的快速随机行

php - woocommerce PayPal 链接错误 - 逗号而不是点

css - 有没有办法将样式表的优先级设置为高于 !important?

php - Woocommerce 产品自定义字段 : Check if the input already exist

javascript - 从一段文本中找出javascript中的关键字

javascript - javascript 在 WordPress 中应该放在哪里,只有 single.php 才需要?

php - 删除 WooCommerce 中最小购物车总数和特定国家/地区的所有税费