Применить процентную скидку на товары в корзине Woocommerce для новых клиентов - PullRequest
0 голосов
/ 19 декабря 2018

Мы используем Klarna Checkout (сторонний плагин) для обработки платежей для нашей платформы WooCommerce.

Когда продукт добавляется в корзину, появляется форма Klarna Checkout с деталями, такими как email и контактный номер .

Когда пользователь вводит свою электронную почту, я определяю, является ли она новой электронной почтой, предоставляющей 50% скидку :

our-custom.js

  var j = jQuery.noConflict();
  // check every second if email is filled
  var check_is_email_done = setInterval(function() {
    var is_email_done = j('.klarna-widget-form-user .email').text();

    if(is_email_done.length > 0) {
      console.log('email is filled: ' + is_email_done);
      var notFound = j('.fortnox-users td').filter(function(){ 
        return j(this).text() == is_email_done;
      }).get();

      var token = notFound.length;
      if(token > 0) {
        console.log('Old customer..');
      } else { 

        console.log('New customer..');

        // call new_customer_discount() method in functions.php
        j.ajax({
          type: 'GET',
          url: ajaxurl,
          cache: false,
          data: { action: 'newcustomerdiscount'},
          success: function(data) {

            console.log('newcustomerdiscount' + data);

          },
          error: function(xhr,status,error) {
            console.log('newcustomerdiscount error:'+error);

          }
        });

      }

      clearInterval(check_is_email_done);
    }

  },1000);

functions.php

function new_customer_discount() {
  //echo "new_customer_discount123";
  $my_total = wc_format_decimal(WC()->cart->total, 2);

  echo 'Total: '.$my_total;


  do_action('woocommerce_calculate_totals', function($cart) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    print_r($cart);  
    $computed_price = 0;

    // Loop Through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Get the product id (or the variation id)
        $product_id = $cart_item['data']->get_id();

        // GET THE NEW PRICE (code to be replace by yours)
        if($computed_price > 0)
          $prod_price = $computed_price * .50; // 50% discount

        // Updated cart item price
        $cart_item['data']->set_price( $prod_price );
    }


  });

}

Поток моего кода выше, когда я определяю, является ли клиентЭто новый, я вызываю метод new_customer_discount() в functions.php , затем выполняю do_action с обратным вызовом

Знаете ли вы, как правильно выполнить вышеописанный хук в functions.php?Любая помощь очень ценится.Спасибо

1 Ответ

0 голосов
/ 19 декабря 2018

Поскольку я не могу проверить ваш код jQuery, допустим, что запрос jQuery Ajax работает.Теперь, чтобы изменить цены товаров в корзине, вам нужно вместо этого использовать woocommerce_before_calculate_totals, а в своем php Ajax вы будете использовать WC_Session

. В вашем коде jQuery вам может понадобиться добавить в часть success следующеестрока:

j('body').trigger('update_checkout'); // Refresh checkout

Таким образом, ваш код PHP будет:

add_action('wp_ajax_nopriv_newcustomerdiscount', 'ajax_customer_discount');
add_action('wp_ajax_newcustomerdiscount', 'ajax_customer_discount');
function ajax_customer_discount() {
    WC()->session->set('new_customer', true);
}



add_action('woocommerce_before_calculate_totals', 'set_new_customer_discount', 100, 1 );
function set_new_customer_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // If it's not a new customer we exit
    if( ! WC()->session->get('new_customer') )
        return; // Exit

    // Loop Through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // 50% items discount
        $cart_item['data']->set_price( $cart_item['data']->get_price() / 2 ); 
    }
}

Код помещается в файл function.php вашей активной дочерней темы (или активной темы).Протестировано и работает, когда WC()->session->get('new_customer') равно true

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...