Search code examples
phpcsswordpresswoocommercediscount

How to add a CSS class for the displayed discounted percentage near sale price on single product pages in WooCommerce


I using "Display the discounted percentage near sale price in Single product pages for WC 3.0+" (Original answer code)

I used this code to show sale percentage after price on single product page. but I want to customize it - to give it background, paddings, etc...

So I need to include CSS class name in that function to be able to customize it via CSS

I want to add it only to "-percentage" (I don't want it to be applied neither to discounted or regular price)


Solution

  • Some additional information

    So you get

    function woocommerce_custom_sales_price( $price, $regular_price, $sale_price ) {
        $percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
        $percentage_txt = '<span class="my-class">' . __('-', 'woocommerce' ) . $percentage . '</span>';
        $price = '<del>' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '</del>
        <ins>' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) . $percentage_txt : $sale_price . $percentage_txt ) . '</ins>';
    
        return $price;
    }
    add_filter( 'woocommerce_format_sale_price', 'woocommerce_custom_sales_price', 10, 3 );