Get Product Discount Percentage.php

Implement scripts to retrieve discounted product percentages.

<?php    
    global $product; // or use wc_get_product($product_id) function to get the product object

    $percentage = 0;
    if (is_object($product) && method_exists($product, 'is_on_sale') && $product->is_on_sale()) {
        if ($product->get_type() == 'variable') {
            $max_percentage = 0;
            $available_variations = $product->get_variation_prices();
            foreach ($available_variations['regular_price'] as $key => $regular_price) {
                $sale_price = $available_variations['sale_price'][$key];
                if (function_exists('wc_get_product')) {
                    $product_variation = wc_get_product($key);
                    $discount = apply_filters('advanced_woo_discount_rules_get_product_discount_price_from_custom_price', false, $product_variation, 1, 0, 'all', true, false);
                    if ($discount !== false && is_array($discount) && isset($discount['initial_price']) && isset($discount['discounted_price'])) {
                        $regular_price = $discount['initial_price'];
                        $sale_price = $discount['discounted_price'];
                    }
                }
                if ($sale_price < $regular_price) {
                    $percentage = round((($regular_price - $sale_price) / $regular_price) * 100);
                    if ($percentage > $max_percentage) {
                        $max_percentage = $percentage;
                    }
                }
            }
            $percentage = $max_percentage;
        } elseif ($product->get_type() == 'simple' || $product->get_type() == 'external' || $product->get_type() == 'variation') {
            $discount = apply_filters('advanced_woo_discount_rules_get_product_discount_price_from_custom_price', false, $product, 1, 0, 'all', true, false);
            if ($discount !== false && is_array($discount) && isset($discount['initial_price']) && isset($discount['discounted_price'])) {
                $percentage = round((($discount['initial_price'] - $discount['discounted_price']) / $discount['initial_price'])  * 100);
            } elseif ($product->get_sale_price() != '') {
                $percentage = round((($product->get_regular_price() - $product->get_sale_price()) / $product->get_regular_price()) * 100);
            }
        }
    }

    if ($percentage > 0) {
        echo $percentage; // here you can get the product discount percentage
    }