Home > OS >  Add a custom text before the sale price in WooCommerce
Add a custom text before the sale price in WooCommerce

Time:08-10

Add a custom text before the price if the product has a sale price in WooCommerce

function add_custom_text_before_sale_prices( $price, $product ) {
    // Text
    $text_regular_price = __("Regular Price: ");
    $text_final_price = __("Final Price: ");

    if ( $product->is_on_sale() ) {
        $has_sale_text = array(
          '<del>' => '<del>' . $text_regular_price,
          '<ins>' => '<br>'.$text_final_price.'<ins>'
        );
        
        $return_string = str_replace(
            array_keys( $has_sale_text ), 
            array_values( $has_sale_text ), 
            $price
        );
        
        return $return_string;
    }
    return $price;
} `add_filter( 'woocommerce_get_price_html', 'add_custom_text_before_sale_prices', 100, 2 );`

But I am getting output - USD100.00 Final Price: USD50.00

But I want Regular Price: USD100.00 Final Price: USD50.00

CodePudding user response:

you can use this code for it

add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );
function cw_change_product_price_display( $price ) {
    // Your additional text in a translatable string
    $text = __('TEXT');

    // returning the text before the price
    return $text . ' ' . $price;
}

CodePudding user response:

Here are two snippets of code you can use, You can add in an active child theme function.php file.

Method 1: Add text before regular price and sale price

//Add text before regular price and sale price

function vh_rp_sale_price_html( $price, $product ) {
  if ( $product->is_on_sale() ) :
     $has_sale_text = array(
      '<del>' => '<del>Regular Price: ',
      '<ins>' => '<br>Sale Price: <ins>'
    );
    $return_string = str_replace(array_keys( $has_sale_text ), array_values( $has_sale_text ), $price);
   else :
     $return_string = 'Regular Price: ' . $price;
     endif;
     return $return_string;
 }
 add_filter( 'woocommerce_get_price_html', 'vh_rp_sale_price_html', 100, 2 );

Method 2: Add text before regular price only

//Add text before regular price only

function vh_rp_price_html( $price, $product ) {
   $return_string = 'Regular Price: ' . $price;
   return $return_string;
}
add_filter( 'woocommerce_get_price_html', 'vh_rp_price_html', 100, 2 );

See the attachment Output enter image description here

  • Related