如何在 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 恤的价格可能较低。 For cases like these, WooCommerce displays the sale price range below the product title, while the regular & sale prices of each variation of the product is displayed above the Add to Cart button when the variation is selected. 下图说明了这一点:

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
从下拉列表中选择变体时,在产品标题下方显示变体价格和“您节省 %”。