Remove zeros on WooCommerce (3 ways)

Blog

Posted by Nuno Marques on 7 Dec 2018

Introduction

Zeros in prices on WooCommerce websites can sometimes clutter the user experience or create inconsistencies, especially in specific contexts like invoice generation. In this post, we'll explore three different methods to remove these zeros, each catering to different requirements and scenarios.

Tutorial

First Way — Remove Zeros Globally (Front-end/Backend):

The first approach, taken from the official WooCommerce documentation, globally removes zeros from prices. While effective for most situations, it may not be suitable if you need to retain zeros for backend processes like generating invoice PDFs.

/**
 * Trim zeros in price decimals
 **/
add_filter( 'woocommerce_price_trim_zeros', '__return_true' );

Second Way — Removing ".00" with JavaScript (Front-end Only)

For front-end modifications only, you can utilize JavaScript to remove ".00" from displayed prices. This method ensures a seamless user experience without affecting backend functionality.

function remove_zeros() {
?>
  <script>
    jQuery(document).ready(function($){
      $('.amount').text(function(index, text) {
        return text.replace(/.00/g, '');
      });
    });
  </script>
<?php
}

add_action( 'wp_footer', 'remove_zeros' );

Third Way — Create a Function for Front-end Operation:

This method, suggested after collaboration on Slack, offers a balanced solution by conditionally trimming zeros only on the front end. It ensures consistency in user experience while preserving backend functionality.

function conditionally_trim_zeros( $trim ) {
  if ( ! is_admin() ) {
    $trim = true;
  }
  return $trim;
}

add_filter( 'woocommerce_price_trim_zeros', 'conditionally_trim_zeros' );

Conclusion

By exploring these three methods, you can effectively remove zeros from prices on your WooCommerce website, catering to different needs and scenarios. Whether you require a global solution or a front-end-specific adjustment, these approaches offer flexibility and versatility to enhance your user experience.