如何在 WooCommerce 中簡單和可變產品的銷售價格下方顯示“您節省 x%”

已發表: 2019-04-03

我們都知道折扣如何吸引客戶並增加銷售額。 但如今,僅顯示您以較低的價格出售商品是不夠的,所有零售商和電子商務網站都同時提供折扣。 當只顯示新舊價格時,客戶需要進行數學計算以計算他實際節省了多少。 處理此問題的更好方法是顯示客戶在購買時節省的金額的百分比。 這為他們提供了更好的想法和更簡單的方法來決定是否進行購買。 讓我們看看如何在 WooCommerce 中簡單和可變產品的銷售價格旁邊顯示“You Save x%”。

如何在簡單產品的銷售價格以下顯示您節省 %

一旦知道常規價格和銷售價格,對於簡單產品來說,顯示節省金額的百分比就很容易了。 在正常情況下,簡單產品的這些價格顯示如下:

display “You Save x%” below sale prices for simple and variable products in WooCommerce - Default simple product page
銷售簡單產品的默認顯示

將以下代碼添加到您的子主題的functions.php 文件中,將在簡單產品的價格下方顯示“You Save x%”,以便用戶立即了解交易的好壞。

 功能 ts_you_save() {
  
  全球$產品;
  
   if( $product->is_type('simple') || $product->is_type('external') || $product->is_type('grouped') ) {
      
     	$regular_price = get_post_meta( $product->get_id(), '_regular_price', true ); 
        $sale_price = get_post_meta( $product->get_id(), '_sale_price', true );
     
     	如果(!empty($sale_price)){
  
              $amount_saved = $regular_price - $sale_price;
              $currency_symbol = get_woocommerce_currency_symbol();

              $percentage = round( ( ( $regular_price - $sale_price ) / $regular_price ) * 100 );
              ?>
              <p><b>你保存:<?php echo number_format($percentage,0, '', '').'%'; ?></b></p>				
              <?php		
        }
   }
}

add_action('woocommerce_single_product_summary','ts_you_save',11);

在這個代碼片段中,我們在內置的 WooCommerce 鉤子woocommerce_single_product_summary中添加了一個函數ts_you_save() ,它指向產品標題下方的區域。 函數ts_you_save()識別產品的類型併計算產品在銷售時節省的金額百分比。 通過添加一些 CSS,您可以按照您想要的方式打印它:

display “You Save x%” below sale prices for simple and variable products in WooCommerce - You Save Percentage Displayed for a Simple Product
在簡單產品的售價下方顯示“You Save %”

如果要顯示節省的金額和百分比,可以通過以下方式稍微修改相同的代碼段:

 功能 ts_you_save() {
  
  全球$產品;
  
   if( $product->is_type('simple') || $product->is_type('external') || $product->is_type('grouped') ) {
      
     	$regular_price = get_post_meta( $product->get_id(), '_regular_price', true ); 
        $sale_price = get_post_meta( $product->get_id(), '_sale_price', true );
     
     	如果(!empty($sale_price)){
  
              $amount_saved = $regular_price - $sale_price;
              $currency_symbol = get_woocommerce_currency_symbol();

              $percentage = round( ( ( $regular_price - $sale_price ) / $regular_price ) * 100 );
              ?>
              <p><b>你省了:<?php echo number_format($amount_saved,2, '.', '')." (".number_format($percentage,0, '', '')."%)" ; ?></b></p>						
              <?php		
        }
   }
}

add_action('woocommerce_single_product_summary','ts_you_save',11);

number_format函數是一個內置的 PHP 函數,它接受 4 個參數:

  1. 數字或在我們的例子中,分別是節省的金額和百分比(我們已經使用了兩次該函數)。
  2. 小數位數。 我們將節省的金額設置為 2,將百分比設置為 0,因為我們不希望顯示百分比的任何十進制值。
  3. 您希望使用的小數分隔符。 我們已將其設置為一個點 (.) 用於保存的金額和一個空白值用於百分比。
  4. 千位分隔符。 如果節省的金額超過 1000,則可以使用此參數。 我們目前已將其設置為空白。

保存的金額以及百分比現在將顯示在價格下方:

display “You Save x%” below sale prices for simple and variable products in WooCommerce - You Save Amount and Percentage Displayed for a Simple Product
顯示金額低於簡單產品售價的“You Save %”

如何顯示您節省的百分比低於可變產品的銷售價格

當涉及到可變產品時,這變得很棘手,因為產品的每個變體都可能有不同的價格。 例如,一件大號的 T 恤的價格可能較高,而同一件小號的 T 恤的價格可能較低。 對於此類情況,WooCommerce 在產品標題下方顯示銷售價格範圍,而當選擇變體時,產品每個變體的常規和銷售價格顯示在“添加到購物車”按鈕上方。 下圖說明了這一點:

display “You Save x%” below sale prices for simple and variable products in WooCommerce - Variable Product with Variation Selected
根據不同的變體選擇具有不同價格的在售可變產品的變體

在這種情況下,我們將打印“您節省”文本以及節省的百分比,低於為特定變體顯示的價格。 您需要將代碼片段添加到您的子主題functions.phpfooter.php文件中。

您將在 footer.php 文件中添加的以下代碼片段包含一個在更改變體時觸發的函數。 在我們的例子中,這是在使用尺寸下拉選擇或更改尺寸變化時觸發的。 此函數捕獲特定的變體 id 並通過 ajax 調用將其發送到 functions.php。

 <腳本>
jQuery(文檔).ready(函數($) {
             
  $('input.variation_id').change(function(){
    	
    if( '' != $('input.variation_id').val() ) {
                     
        	        var var_id = $('input.variation_id').val(); // 您選擇的變體 ID
      $.ajax({
        url: "https://<your_woocommerce_site_url>/wp-admin/admin-ajax.php",
        		        數據:{'action':'ts_calc_percentage_saved','vari_id': var_id},
        		        成功:函數(數據){

              如果(數據>0)
          {
            $( ".woocommerce-variation-price" ).append( "<p>You Save: "+data+"%</p>");
          }
        		         },
        		        錯誤:函數(errorThrown){
           			        console.log(errorThrown);
        		         }
    		        });                       
          }
   });
});
</腳本>

您需要將<your_woocommerce_site_url>替換為您的 WooCommerce 網站的基本 URL。

您將在 functions.php 文件中添加的以下代碼片段包含一個函數ts_calc_percentage_saved ,它根據變體 id 獲取產品的正常價格和銷售價格,計算百分比並將其返回到頁腳中的 ajax 函數。 .php 文件。

 //這是在WordPress中掛鉤由ajax調用的函數的方式
add_action("wp_ajax_ts_calc_percentage_saved", "ts_calc_percentage_saved");

//下面的函數是通過footer.php中的ajax腳本調用的
函數 ts_calc_percentage_saved(){
          // $_REQUEST 包含通過 ajax 發送的所有數據
   		if ( isset($_REQUEST) ) {
       		        $百分比=0;
     			$variation_id = sanitize_text_field($_REQUEST['vari_id']);
                        $variable_product = wc_get_product($variation_id);
                        $regular_price = $variable_product->get_regular_price();
                        $sale_price = $variable_product->get_sale_price();
     
       			如果(!empty($sale_price)){
  
                             $amount_saved = $regular_price - $sale_price;
                             $currency_symbol = get_woocommerce_currency_symbol();

                             $percentage = round( ( ( $regular_price - $sale_price ) / $regular_price ) * 100 );
     			}
     			死($百分比);
   		}
}

sanitize_text_field()函數是一個 WordPress 函數,它有助於清理我們從客戶端收到的輸入。

因此,您現在將看到“您節省了”以及節省的金額百分比,低於變化的價格。

display “You Save x%” below sale prices for simple and variable products in WooCommerce - Variable Product with You Save Percentage Displayed below the Variation Price
當從下拉列表中選擇變體時,在變體價格下方顯示“You Save %”。

您可以在 ajax 函數本身中設置任何您希望的樣式,方法是在此行的 append 函數中添加 HTML 和 CSS:

$( “.woocommerce-variation-price” ).append( “<p>You Save: “+data+”%</p>”);

在產品標題下方而不是可變產品的“添加到購物車”按鈕上方顯示 You Save %

如果您願意,您可以在產品標題下方而不是在“添加到購物車”按鈕上方顯示您保存的文本以及保存的百分比,方法是向上述代碼片段添加更多代碼片段。

除了上面提到的代碼片段(在footer.php 和functions.php 文件中)之外,應該將這段代碼添加到您的子主題的functions.php 文件中。

 //下面的代碼是改變價格

函數 ts_shuffle_variable_product_elements(){
    如果 ( is_product() ) {
        全球 $post;
        $product = wc_get_product($post->ID);
        if ( $product->is_type( '變量' ) ) {
            remove_action('woocommerce_single_variation','woocommerce_single_variation',10);
            add_action('woocommerce_before_variations_form','woocommerce_single_variation',20);

            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);
            add_action('woocommerce_before_variations_form','woocommerce_template_single_title',10);

            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20);
            add_action('woocommerce_before_variations_form','woocommerce_template_single_excerpt',30);
        }
    }
}
add_action('woocommerce_before_single_product','ts_shuffle_variable_product_elements');

這段代碼的本質是刪除元素(包括標題)並按照您想要的方式重新排列它們。 結果是價格範圍被刪除,並且當您選擇變體時顯示變體價格,以及它下方的 You Save 文本,如圖所示:

display “You Save x%” below sale prices for simple and variable products in WooCommerce - Variable Product with Variation Price and You Save Percentage Displayed below the Product Title
從下拉列表中選擇變體時,在產品標題下方顯示變體價格和“您節省 %”。