Heute zeigen wir Ihnen, wie man die Prozentzahlen im Discount-Badge ohne Plungins anzeigt. Der Code sorgt dafür, dass nicht nur ein simples %-Zeichen im Artikel-Listing angezeigt wird, wenn ein Rabat für den Artikel vorhanden ist, sondern die genaue Prozentzahl anzeigt.
Um Discount-Badges mit einem Rabattprozentsatz in Ihrem WooCommerce Shop anzuzeigen, können Sie den untenstehenden Code in die functions.php Ihres aktuellen Themes kopieren.
add_action( 'woocommerce_before_shop_loop_item_title', 'custom_sale_badge', 25 ); function custom_sale_badge() { // Globale Variable mit dem Produkt global $product; // Prüfen, ob es Sale Artikel ist if ( ! $product->is_on_sale() ) { return; } // kein Variables Produkt if ( $product->is_type( 'simple' ) ) { // Rabattprozentansatz berechnen $percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100; } elseif ( $product->is_type( 'variable' ) ) { // Variables Produkt $percentage = 0; // Schleife für jedes Produkt foreach ( $product->get_children() as $variation_id ) { $variation = wc_get_product( $variation_id ); // Schleife, wenn Artikel nicht rabattiert ist if( ! $variation->is_on_sale() ) { continue; } // Preis ohne Rabatt $regular_price = $variation->get_regular_price(); // Sale Preis $sale_price = $variation->get_sale_price(); // Rabattprozentsatz $variation_percentage = ( $regular_price - $sale_price ) / $regular_price * 100; if ( $variation_percentage > $percentage ) { $percentage = $variation_percentage; } } } if ( $percentage > 0 ) { echo '<div class="custom-sale-badge">' . round( $percentage ) . '%</div>'; } }
Bemerkung zum Code:
.custom-sale-badge { background-color: #D9534F; display: inline-block; padding: 2px 5px; font-size: 14px; color: #fff; border-radius: 4px; margin: 0 0 10px 0; }