I would like to overwrite the name/title of single products on the category and the product page also, with an existing ‘customname1’ custom field.
The change should be applied whenever the ‘customname1’ field is present.
I have found a modification for the checkout and the cart page as the following. I would like to have the same effect on the Category and the Product page.
function woocommerce_update_product_title($title, $cart_item){
if( is_checkout() || is_cart() ) : //Check Checkout or Cart Page
$customname1= get_post_meta($cart_item['product_id'], 'customname1',true);
return !empty( $customname1) ? $customname1: $title;
endif;
return $title;
}
add_filter('woocommerce_cart_item_name', 'woocommerce_update_product_title', 10, 2);
2
Answers
Certainly! To achieve the same effect on the category and product pages, you can use filters specific to those pages. For the product page, you can use the woocommerce_single_product_summary hook, and for the category page, you can use the woocommerce_before_shop_loop_item_title hook.
Here’s the modified code:
}
// Hook for product page
add_filter( ‘the_title’, ‘woocommerce_update_product_title’, 10, 2 );
// Hook for category page
add_filter( ‘woocommerce_before_shop_loop_item_title’, ‘woocommerce_update_product_title’, 10, 2 );
This code checks if you are on a product page using is_product() and updates the title accordingly. If you are on the category page or the shop page, it checks for the presence of the ‘customname1’ custom field and updates the title if it exists.
Make sure to adjust the hooks and conditions based on your specific requirements and theme structure.
Instead, you should use the following code replacement, that will work for everywhere, replacing your current provided code. The following hooked functions will change or filter the product title or name, based on your custom field value, when any code is using
get_title()
orget_name()
methods:Code goes in functions.php file of your child theme (or in a plugin). Tested and works.