Search code examples
sliderhookpercentagebadgediscount

How we display discount percentage badge and sale badge separately on WooCommerce product?


Want to display discount percentage badge on right hand side of product image and sale badge on left hand side of product image in products slider. So, Please Suggest some hooks for this functionality!

Tried to add the following hook but it will replace the existing sale badge with the discount percentage badge on shop page and also this hook is not working for the product slider on homepage.

add_filter('woocommerce_sale_flash', 'add_percentage_to_sale_bubble'); function add_percentage_to_sale_bubble( $html ) { global $product; $percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 ); $output =' <span class="onsale">'.$percentage.'%</span>'; return $output; }


Solution

  • you can use the following hook

    add_filter( 'woocommerce_get_price_html', 'change_displayed_sale_price_html', 10, 2 );
    
    function change_displayed_sale_price_html( $price, $product ) {
    
         // Only on sale products on frontend and excluding min/max price on variable products
         if( $product->is_on_sale() && ! is_admin() && $product->is_type('simple') ){
    
            // Get product prices
            $regular_price = (float) $product->get_regular_price();    // Regular price
    
           // Active price (the "Sale price" when on-sale)
           $sale_price = (float) $product->get_price(); 
    
           // "Saving Percentage" calculation and formatting
           $precision = 0; // Max number of decimals
           $saving_percentage = round( 100 - ( $sale_price / $regular_price * 100 ), $precision ) . '%';
    
           // Append to the formated html price
           $price .= sprintf( __('<p class="saved-sale">%s</p>', 'woocommerce' ), $saving_percentage );
        }
        return $price;
    }