如果該專案正在出售,預設的 WooCommerce 會顯示 「銷售」 徽章,但是如何顯示確切的銷售百分比呢?
我為自己的一位客戶實現了這一點,所以在這裡您可以輕鬆地解決問題!

WooCommerce 3.0+ PHP 程式碼片段:顯示折扣百分比 @迴圈頁面 – WooCommerce
/** * @snippet Display Discount Percentage @ Loop Pages - WooCommerce * @sourcecode https://businessbloomer.com/?p=21997 * @author Rodolfo Melogli * @compatible WC 3.1.0 */ add_action( 'woocommerce_before_shop_loop_item_title', 'bbloomer_show_sale_percentage_loop', 25 ); function bbloomer_show_sale_percentage_loop() { global $product; if ( $product->is_on_sale() ) { if ( ! $product->is_type( 'variable' ) ) { $max_percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100; } else { $max_percentage = 0; foreach ( $product->get_children() as $child_id ) { $variation = wc_get_product( $child_id ); $price = $variation->get_regular_price(); $sale = $variation->get_sale_price(); if ( $price != 0 && ! empty( $sale ) ) $percentage = ( $price - $sale ) / $price * 100; if ( $percentage > $max_percentage ) { $max_percentage = $percentage; } } } echo "<div class='sale-perc'>-" . round($max_percentage) . "%</div>"; } }
PHP 程式碼片段:顯示折扣百分比 @迴圈頁面 – WooCommerce
/** * @snippet Display Discount Percentage @ Loop Pages - WooCommerce * @sourcecode https://businessbloomer.com/?p=21997 * @author Rodolfo Melogli * @compatible WC 2.6.14, WP 4.7.2, PHP 5.5.9 */ add_action( 'woocommerce_before_shop_loop_item_title', 'bbloomer_show_sale_percentage_loop', 25 ); function bbloomer_show_sale_percentage_loop() { global $product; if ( $product->is_on_sale() ) { if ( ! $product->is_type( 'variable' ) ) { $max_percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 ); } else { foreach ( $product->get_children() as $child_id ) : $variation = $product->get_child( $child_id ); $price = $variation->get_regular_price(); $sale = $variation->get_sale_price(); $percentage = $price != 0 && ! empty( $sale ) ? ( ( $price - $sale ) / $price * 100 ) : $max_percentage; if ( $percentage >= $highest_percentage ) : $max_percentage = $percentage; $regular_price = $product->get_variation_regular_price( 'min' ); $sale_price = $product->get_variation_sale_price( 'min' ); endif; endforeach; } echo "<div class='sale-perc'>-" . round($max_percentage) . "%</div>"; } }
還有一點 CSS:
.sale-perc { background-color: #D9534F; display: inline; padding: .2em .6em .3em; font-size: 75%; font-weight: bold; color: #fff; text-align: center; border-radius: .25em; }
如何新增此程式碼?
1 、您可以將 PHP 程式碼片段放置在主題或子主題的 functions.php 檔案的底部 (如果是 CSS 程式碼,請新增到子主題的 style.css 檔案底部) 修改之前建議先備份原始檔案,若出現錯誤請先刪除此程式碼。
2 、 WordPress 4.9 後改進了主題編輯器,對於 CSS 程式碼也可開啟網站前臺編輯器的 【自定義】,複製程式碼新增到自定義 css 中。
此程式碼是否可用?
如需幫助或是您有更好的方案想分享?請到薇曉朵 WooCommerce 中文論壇留言告知,我們希望可以幫到更多國內的 WooCommerce 使用者也希望您的參與。