Jean R.
Jean R.

Reputation: 534

How to programmaticaly change product name everywhere in woocommerce?

I'm trying to beautify my products names and I need to apply the changes everywhere (catalog, cart, checkout, widgets...) etc

Actually, I managed to :

Catalog (loop) single product :

add_filter('the_title', 'new_title', 10, 2);
function new_title($title, $id) {
    if('product' == get_post_type($id)){
        $title = rename_woo_product($title, $id); // My function to rename
    }
    return $title;
}

In the product title tag and yoast :

add_filter( 'pre_get_document_title', 'generate_custom_title', 10 );
add_filter('wpseo_title', 'generate_custom_title', 15);
function generate_custom_title($title) {
    if(  is_singular( 'product') ) {
        $title = get_the_title();
    }
    return $title;
}

Cart & Checkout :

add_filter( 'woocommerce_cart_item_name', 'custom_variation_item_name', 10, 3 );
function custom_variation_item_name( $item_name,  $cart_item,  $cart_item_key ){
    $product_item = $cart_item['data'];

    $item_name = get_the_title( $cart_item['product_id'] );

    if(!empty($product_item) && $product_item->is_type( 'variation' ) ) {
        $item_name = $item_name . '<br>' . $cart_item['data']->attribute_summary;
    }

    if(is_cart()){
        $item_name = sprintf( '<a href="%s">%s</a>', esc_url( $cart_item['data']->get_permalink() ), $item_name );
    }

    return $item_name;
}

I don't know if it's the best way to do it, but it works for this. But for example I use the Recent Viewed Products widget of woocommerce, and the product title is not updated.. Same thing for Yith Wishlist

Is there a better way to update products names and apply it everywhere ?

Upvotes: 3

Views: 2402

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

You may use also use the composite hook woocommerce_product_get_name like:

add_filter('woocommerce_product_get_name', 'filter_wc_product_get_name', 10, 2); // For "product" post type
add_filter('woocommerce_product_variation_get_name', 'filter_wc_product_get_name', 10, 2); // For "product_variation" post type
function filter_wc_product_get_name( $name, $product ){
    if ( ! is_admin() ) {
        $name = rename_woo_product($name, $product->get_id());
    }
    return $name;  
}

It should replace your custom function hooked in woocommerce_cart_item_name filter hook.

Upvotes: 3

Related Questions