php 在WooCommerce购物车页面应用优惠券不会刷新总数

col17t5w  于 2023-09-29  发布在  PHP
关注(0)|答案(1)|浏览(137)

我目前正在我的WooCommerce cart.php页面上实现 AJAX 功能。其目标是使用户能够应用优惠券,而无需刷新整个页面。虽然我已经取得了进展,我遇到了一个障碍-应用的优惠券没有更新购物车总数的预期。
问题截图:

cart.php coupon form:

<?php if ( wc_coupons_enabled() ) { ?>
        <form class="checkout_coupon mb-0" method="post">
            <h1 class="cart-small-title">Discount Code</h1>
            <div class="main_cou_nav">
                <p class="cc_code">Coupon Code</p>
                <div class="coupon">
                    <h3 class="widget-title"><?php echo get_flatsome_icon( 'icon-tag' ); ?> <?php esc_html_e( 'Coupon', 'woocommerce' ); ?></h3><label for="coupon_code" class="screen-reader-text"><?php esc_html_e( 'Coupon:', 'woocommerce' ); ?></label><input type="text" name="coupon_code" class="input-text" id="coupon_code" value="" placeholder="<?php esc_attr_e( 'Enter Your Coupon code', 'woocommerce' ); ?>" /> <button type="button" class="is-form expand button<?php if ( fl_woocommerce_version_check( '7.0.1' ) ) { echo esc_attr( wc_wp_theme_get_element_class_name( 'button' ) ? ' ' . wc_wp_theme_get_element_class_name( 'button' ) : '' ); } ?>" id="apply_coupon" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>"><?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?></button>
                  <?php do_action( 'woocommerce_cart_coupon' ); ?>
                  <div id="custom-coupon-notice"></div>
                </div>
            </div>
        </form>

        <?php } ?>

functions.php:

function enqueue_my_custom_script() {
  wp_enqueue_script(
    'ajax-script-cart', // Handle for your script
    get_stylesheet_directory_uri() . '/js/custom-cart.js', // Path to your script
    array('jquery'), // Dependencies (jQuery as an example)
    '6.0.0', // Version number
    true // Load in the footer
  );

  wp_localize_script(
    'ajax-script-cart', // Handle for your script
    'wc_cart_params', // Name for the JavaScript object
    array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) // Data to pass to the script
  );
}

add_action('wp_enqueue_scripts', 'enqueue_my_custom_script');

function ajax_apply_coupon_cart() {
  if(!isset($_POST['coupon_code']) || empty($_POST['coupon_code'])) {
    wp_send_json(['success' => false, 'data' => ['message' => 'No coupon code provided']], 200);
    return;
  }

  $coupon_code = sanitize_text_field($_POST['coupon_code']);

  if(!WC()->cart->has_discount($coupon_code)) {
    $coupon_id = wc_get_coupon_id_by_code($coupon_code);

    if(!$coupon_id) {
      wp_send_json(['success' => false, 'data' => ['message' => sprintf(__('Coupon  does not exist!', 'woocommerce'), $coupon_code)]], 200);
      return;
    }

    WC()->cart->apply_coupon($coupon_code);
    wp_send_json_success(['message' => sprintf(__('Coupon  applied successfully.', 'woocommerce'), $coupon_code)], 200);
  } else {
    wp_send_json_error(['message' => sprintf(__('Coupon  is already applied!', 'woocommerce'), $coupon_code)], 200);
  }
}

add_action('wp_ajax_ajax_apply_coupon_cart', 'ajax_apply_coupon_cart');
add_action('wp_ajax_nopriv_ajax_apply_coupon_cart', 'ajax_apply_coupon_cart');

custom-ajax.js:

console.log("Cart script is working")

jQuery(document).on('click', '#apply_coupon', function () {
  console.log("button working as well")
  var code = jQuery('#coupon_code').val();

  data = {
    action: 'ajax_apply_coupon_cart',
    coupon_code: code
  };

  jQuery.post(wc_cart_params.ajax_url, data, function (returned_data) {
    console.log("Data returned from server: ", returned_data); // Log returned data for debugging.
    if(returned_data.success) {
      jQuery('#custom-coupon-notice').html(returned_data.data.message).removeClass('woocommerce-error').addClass('woocommerce-message').show();
    } else {
      jQuery('#custom-coupon-notice').html(returned_data.data.message).removeClass('woocommerce-message').addClass('woocommerce-error').show();
    }
    jQuery(document.body).trigger('updated_wc_div'); // Update the cart page after applying the coupon
  })
    .fail(function (jqXHR) {
      console.error(jqXHR); // Log the entire jqXHR object for debugging.
      var errorData = jqXHR.responseJSON;
      var errorMessage = errorData && errorData.message ? errorData.message : 'An unknown error occurred';
      jQuery('#custom-coupon-notice').html(errorMessage).addClass('woocommerce-error').show();
    });
});
i7uq4tfw

i7uq4tfw1#

默认情况下,在WooCommerce中,购物车中应用的优惠券已经通过 AJAX 制作,因此通常页面不会重新加载(删除优惠券或购物车项目时也是如此,并且更新数量时也是如此。
在您的例子中,您可能已经做了太多的自定义,所以默认的 AJAX 进程不再启用。

因此,如果您无意中禁用了 AJAX 购物车刷新,则以下操作可能不起作用。

在您的代码中,可能缺少calculate_totals()方法,以允许触发购物车计算更新。

function ajax_apply_coupon_cart() {
    if(!isset($_POST['coupon_code']) || empty($_POST['coupon_code'])) {
        wp_send_json(['success' => false, 'data' => ['message' => 'No coupon code provided']], 200);
        // return; // <== Not needed as wp_send_json() throws die();
    }
    $coupon_code = sanitize_text_field($_POST['coupon_code']);
  
    if(!WC()->cart->has_discount($coupon_code)) {
        $coupon_id = wc_get_coupon_id_by_code($coupon_code);
    
        if(!$coupon_id) {
            wp_send_json(['success' => false, 'data' => ['message' => sprintf(__('Coupon  does not exist!', 'woocommerce'), $coupon_code)]], 200);
            // return; // <== Not needed as wp_send_json() throws die();
        }
    
        $result = WC()->cart->apply_coupon($coupon_code); // Apply coupon
        
        if( $result ) {
            WC()->cart->calculate_totals(); // <=== Refresh totals (Missing)

            wp_send_json_success(['message' => sprintf(__('Coupon  applied successfully.', 'woocommerce'), $coupon_code)], 200);
        }
    } else {
        wp_send_json_error(['message' => sprintf(__('Coupon  is already applied!', 'woocommerce'), $coupon_code)], 200);
    }
}
add_action('wp_ajax_ajax_apply_coupon_cart', 'ajax_apply_coupon_cart');
add_action('wp_ajax_nopriv_ajax_apply_coupon_cart', 'ajax_apply_coupon_cart');

如果 AJAX 购物车刷新仍然有效,这应该可以解决这个问题。

相关问题