在 WooCommerce 购物车页面应用优惠券时,总计不会刷新

问题描述 投票:0回答:1

我目前正在努力在我的 WooCommerce cart.php 页面上实现 AJAX 功能。目标是让用户无需刷新整个页面即可应用优惠券。虽然我取得了进展,但我遇到了障碍 - 所应用的优惠券没有按预期更新购物车总数。

问题截图:

cart.php 优惠券表格:

        <?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');

自定义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();
    });
});
php jquery ajax wordpress woocommerce
1个回答
1
投票

默认情况下,在 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 购物车刷新仍然有效,这应该可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.