I want to display the sale percentage under the product title. This is my function in the functions.php page, however I am getting NAN% Off
// Function to calculate and display sale percentage.
function display_sale_percentage() {
global $product;
if ( $product->is_on_sale() ) {
// Get regular and sale prices
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
// Calculate discount percentage
$discount_percentage = round( ( ($regular_price - $sale_price) / $regular_price ) * 100 );
// Display the percentage
echo '<span class="sale-percentage">' . $discount_percentage . '% off</span>';
}
}
// Hook the function to a suitable location in your product archive template.
// For example, you can hook it into the product loop.
add_action( 'woocommerce_before_shop_loop_item_title', 'display_sale_percentage', 25 );
Your code needs to handle variable products and its variations prices.
For variable products, the following code will display
For on sale simple products, the discount percentage will be displayed.
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.