1
votes

I'm experiencing an issue with the output of a custom field within the WooCommerce cart-totals.php template.

I've added custom <tr> markup to the <table> tag found inside cart-totals.php, which is the element that shows your subtotal, taxes, fields to calculate shipping.

My function simply checks for a range of values stored in a custom field and echos text, the issue I'm having is that when I change my shipping option, say from air shipping to ground, the cart updates through ajax and changes my custom field value to empty. This doesn't happen when updating cart quantities, updating totals or on page load, just when changing shipping option.

Any advice to fix this would be much appreciated!

<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>
1

1 Answers

1
votes

Try the following instead (without editing cart_totals.php template). So you will need before to remove temporarily your changes from cart_totals.php template file.

The code:

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>';
}

Code goes in function.php file of your active child theme (or active theme). It should works.

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

enter image description here