Change woocommerce product name/title from a product custom field

150 Views Asked by At

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);
1

There are 1 best solutions below

0
LoicTheAztec On

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() or get_name() methods:

add_filter( 'woocommerce_product_title', 'custom_product_title', 10, 2 );
function custom_product_title( $title, $product ) {
    if ( $custom_title = $product->get_meta('customname1') ) {
        return $custom_title;
    }
    return $title;
}

add_filter( 'woocommerce_product_get_name', 'custom_product_name', 10, 2 );
function custom_product_name( $name, $product ) {
    if ( $custom_name = $product->get_meta('customname1') ) {
        return $custom_name;
    }
    return $name;
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.