WooCommerce で単純な商品と可変商品のセール価格を下回る「You Save x%」を表示する方法

公開: 2019-04-03

割引が顧客を引き付け、売り上げを伸ばす方法は誰もが知っています。 しかし、最近では、すべての小売業者と e コマース Web サイトが同時に割引を提供しているため、より安い価格で商品を販売していることを示すだけでは十分ではありません。 古い価格と新しい価格のみが表示される場合、顧客は、実際に節約できる金額を計算するために計算を行う必要があります。 これを処理するより良い方法は、顧客がその購入を行ったときに節約できる金額のパーセンテージを表示することです。 これにより、購入するかどうかを決定するためのより良いアイデアと簡単な方法が得られます。 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() {
  
  グローバル $product;
  
   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 );
     
     	if( !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() {
  
  グローバル $product;
  
   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 );
     
     	if( !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関数は、4 つの引数を受け入れる組み込みの PHP 関数です。

  1. 数値、または私たちの場合は、それぞれ節約された金額とパーセンテージです (関数を 2 回使用しました)。
  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
バリエーションごとに価格が異なる販売中の可変商品のバリエーションを選択する

この場合、特定のバリエーションで表示される価格の下に、保存されたパーセンテージとともに「You Save」テキストを印刷します。 子テーマfunctions.phpファイルとfooter.phpファイルの両方にコード スニペットを追加する必要があります。

footer.php ファイルに追加する次のコード スニペットには、バリエーションが変更されたときにトリガーされる関数が含まれています。 私たちの場合、これはサイズ ドロップダウンを使用してサイズ バリエーションが選択または変更されたときにトリガーされます。 この関数は、特定のバリエーション ID をキャプチャし、ajax 呼び出しを介して functions.php に送信します。

 <スクリプト>
jQuery(document).ready(function($) {
             
  $('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>お得: "+data+"%</p>");
          }
        		         }、
        		        エラー: 関数 (errorThrown){
           			        console.log(errorThrown);
        		         }
    		        });                       
          }
   });
});
</script>

<your_woocommerce_site_url>を WooCommerce Web サイトのベース URL に置き換える必要があります。

functions.php ファイルに追加する次のコード スニペットには、バリエーション ID に基づいて製品の通常価格と販売価格を取得し、パーセンテージを計算して、フッターの ajax 関数に同じ値を返す関数ts_calc_percentage_savedが含まれています。 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();
     
       			if( !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 関数です。

したがって、バリエーションの価格の下に、節約された金額のパーセンテージとともに「You Save」が表示されます。

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 %」が表示されます。

次の行の append 関数内に HTML と CSS を追加することで、ajax 関数自体の中で好きなようにスタイルを設定できます。

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

可変商品の場合、「カートに追加」ボタンの上ではなく、商品タイトルの下に「You Save %」を表示します

必要に応じて、上記のコード スニペットをいくつか追加することで、[カートに追加] ボタンの上ではなく、製品タイトルの下に保存された割合と共に保存されたテキストを表示できます。

このコードは、上記のコード スニペット (footer.php および functions.php ファイル内) に加えて、子テーマの functions.php ファイルに追加する必要があります。

 //以下のコードは価格をシフトするためのものです

関数ts_shuffle_variable_product_elements(){
    if ( 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
ドロップダウンからバリエーションを選択すると、商品タイトルの下にバリエーション価格と「You Save %」が表示されます。