實用的 WordPress ICP 備案許可管理器

WooCommerce 教程:顯示%折扣在 Shop&Loop 頁面

如果該項目正在出售,默認的 WooCommerce 會顯示 「銷售」 徽章,但是如何顯示確切的銷售百分比呢?

我為自己的一位客户實現了這一點,所以在這裏您可以輕鬆地解決問題!

在 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 用户也希望您的參與。

文章沒看懂?代碼不會用?需要幫助您可以

園長 的頭像