function fb_update_product_discount_meta($product_id) { $product = wc_get_product($product_id); if (!$product) { return; } if ($product->is_type('variable')) { $variations = $product->get_available_variations(); $max_discount_percentage = 0; foreach ($variations as $variation) { $variation_id = $variation['variation_id']; $variation_product = wc_get_product($variation_id); if ($variation_product && $variation_product->is_in_stock()) { $regular_price = (float) $variation_product->get_regular_price(); $sale_price = (float) $variation_product->get_sale_price(); if ($sale_price && $regular_price > $sale_price) { $discount_percentage = round((($regular_price - $sale_price) / $regular_price) * 100); if ($discount_percentage > $max_discount_percentage) { $max_discount_percentage = $discount_percentage; } } } } if ($max_discount_percentage > 0) { update_post_meta($product_id, 'discount_percentage', $max_discount_percentage); } else { delete_post_meta($product_id, 'discount_percentage'); } } else { if ($product->is_in_stock()) { $regular_price = (float) $product->get_regular_price(); $sale_price = (float) $product->get_sale_price(); if ($sale_price && $regular_price > $sale_price) { $discount_percentage = round((($regular_price - $sale_price) / $regular_price) * 100); if ($discount_percentage > 0) { update_post_meta($product_id, 'discount_percentage', $discount_percentage); } else { delete_post_meta($product_id, 'discount_percentage'); } } else { delete_post_meta($product_id, 'discount_percentage'); } } else { delete_post_meta($product_id, 'discount_percentage'); } } } add_action('woocommerce_update_product', 'fb_update_product_discount_meta');