Search code examples
phpwordpresswoocommerceproducthook-woocommerce

Alter Woocommerce product name when price is on sale


We use "NET" to identify products that are on sale. I have written the following code to automatically add or remove NET to/from products as they go on or off sale.

function change_product_titles( $post, $title ) {
    
    if ( !empty( get_post_meta( $post->get_id, '_sale_price', true ))){
        return $title.' NET';
    }else{
        return $title;
    }
}
add_filter( 'woocommerce_product_title', 'change_product_titles', 10, 2 );

This seems pretty simple, but I am not seeing the desired effect anywhere.


Solution

  • You are not using the right hook and the right way… Try the following instead, that will add a suffix to the product title (and the product name) everywhere, when the product is on sale, without any need of constantly updating the product titles:

    add_filter( 'the_title', 'change_product_title', 10, 2 );
    function change_product_title( $post_title, $post_id ) {
        if( get_post_type($post_id) === 'product' ) {
            $product = wc_get_product($post_id);
    
            if( is_a($product, 'WC_Product') && $product->get_sale_price() > 0 ) {
                $post_title .= ' NET';
            }
        }
        return $post_title;
    }
    
    add_filter( 'woocommerce_product_variation_get_name', 'change_product_name', 10, 2 );
    add_filter( 'woocommerce_product_get_name', 'change_product_name', 10, 2 );
    function change_product_name( $name, $product ) {
        if ( $product->get_sale_price() > 0 ){
            $name .= ' NET';
        }
        return $name;
    }
    

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

    You will need to remove "NET" from your product titles in the admin.