我想在产品标题下显示销售百分比.这是我在functions.php页面的函数,但我得到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 );