避免在 Woocommerce 中的更新购物车总计 ajax 事件中清除自定义字段值

Avoid custom field value to be cleared on update cart totals ajax event in Woocommerce

我遇到了 WooCommerce 购物车-totals.php 模板中自定义字段输出的问题。

我已将自定义 <tr> 标记添加到 cart-totals.php 内的 <table> 标签,这是显示您的小计、税金、计算运费的字段的元素。

我的函数只是检查存储在自定义字段中的一系列值并回显文本,我遇到的问题是当我更改运输选项时,比如从空运到陆运,购物车通过 ajax 并将我的自定义字段值更改为空。这不会在更新购物车数量、更新总计或页面加载时发生,只会在更改运输选项时发生。

任何解决此问题的建议都将不胜感激!

<table cellspacing="0" class="shop_table shop_table_responsive">

  <tr class="cart-tier-discount">

    <th>Rewards Discount</th>

    <td>

      <?php
        $progress = get_the_author_meta( 'tier_progress_value', $user->ID );

        if ( $progress > 0.01 && $progress < 150 ) {
          echo '0%';
        }
        if ( $progress >= 150 && $progress < 300 ) {
          echo '10%';
        }
        if ( $progress >= 300 && $progress < 500 ) {
          echo '15%';
        }
        if ( $progress >= 500 ) {
          echo '20%';

        } 
      ?>

    </td>

  </tr> 

</table>

改为尝试以下操作 (不编辑 cart_totals.php 模板)。因此,您需要先从 cart_totals.php 模板文件中暂时删除您的更改。

代码:

add_action('woocommerce_cart_totals_before_shipping', 'cart_totals_rewards_before_shipping'  );
function cart_totals_rewards_before_shipping() {
    // Only for logged in users
    if ( ! is_user_logged_in() ) return;

    $progress = (int) get_user_meta( get_current_user_id(), 'tier_progress_value', true );

    if ( $progress >= 0 && $progress < 150 )
        $percentage = '0%';
    elseif ( $progress >= 150 && $progress < 300 )
        $percentage = '10%';
    elseif ( $progress >= 300 && $progress < 500 )
        $percentage = '15%';
    else
        $percentage = '20%';

    echo  '<tr class="cart-tier-discount">
    <th>' . __("Rewards Discount", "") . '</th>
    <td>' . $percentage .'</td>
    </tr>';
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。它应该有效。

Then when changing the shipping method on cart totals update event, the value is still there: