Created
September 26, 2025 16:06
-
-
Save marrisonlab/6183d08d62a3cd9496f1ccb0006bc4b9 to your computer and use it in GitHub Desktop.
Discount % in Jetengine product listing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| add_shortcode( 'sale_percentage', function( $atts ) { | |
| $atts = shortcode_atts( array( | |
| 'id' => get_the_ID(), | |
| ), $atts, 'sale_percentage' ); | |
| $product = wc_get_product( $atts['id'] ); | |
| if ( ! $product ) return ''; | |
| $max_percentage = 0; | |
| // 🔸 Se è un prodotto variabile | |
| if ( $product->is_type('variable') ) { | |
| foreach ( $product->get_children() as $child_id ) { | |
| $variation = wc_get_product( $child_id ); | |
| if ( $variation && $variation->is_on_sale() ) { | |
| $regular_price = (float) $variation->get_regular_price(); | |
| $sale_price = (float) $variation->get_sale_price(); | |
| if ( $regular_price > 0 && $sale_price > 0 ) { | |
| $percentage = round( ( ($regular_price - $sale_price) / $regular_price ) * 100 ); | |
| if ( $percentage > $max_percentage ) { | |
| $max_percentage = $percentage; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| // 🔸 Se è un prodotto semplice | |
| else { | |
| if ( $product->is_on_sale() ) { | |
| $regular_price = (float) $product->get_regular_price(); | |
| $sale_price = (float) $product->get_sale_price(); | |
| if ( $regular_price > 0 && $sale_price > 0 ) { | |
| $max_percentage = round( ( ($regular_price - $sale_price) / $regular_price ) * 100 ); | |
| } | |
| } | |
| } | |
| return $max_percentage > 0 ? '-' . $max_percentage . '%' : ''; | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use dynamic field -> Post ID -> custom field output [sale_percentage id="%s"]