I'm looking to hook into the woocommerce_cart_item_name
filter in WooCommerce and would like to display the product ID after the name ONLY for a specific Product.
I'm looking at this code:
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'].')';
}
This indeed returns the name with a product ID but it applies on all Products on my store.
Only want to display the product ID for a specified product. I'm curious how I'd go about doing this?
My Answer:
You can achieve this by adding a condition to check if the product ID matches the specific product ID you want to display the ID for. Here's an updated version of your code:
php
add_filter( 'woocommerce_cart_item_name', 'just_a_test', 10, 3 );
function just_a_test( $item_name, $cart_item, $cart_item_key ) {
// Specify the product ID for which you want to display the ID
$specific_product_id = 123; // Replace 123 with your actual product ID
// Check if the current product ID matches the specific product ID
if ( $cart_item['product_id'] == $specific_product_id ) {
// Display name and product id here instead
$item_name .= ' (' . $cart_item['product_id'] . ')';
}
return $item_name;
}
In this code, we added a condition to check if the product ID in the cart item matches the specific product ID you want to display the ID for. If it matches, we append the product ID to the item name. Otherwise, we return the original item name without the product ID. Just replace `123` with the actual product ID you want to target.
Rate this post
4 of 5 based on 5958 votesComments