DEV Community

Mahbub Rabbani
Mahbub Rabbani

Posted on

4

Format Woocommerce price in javascript according to the Woocommerce settings.

Woocommerce plugin formats the price in javascript for Filter Products by Price widget. You may check out the source.

Here, I will try to show you how we can achieve this feature.

Let's create a class named PriceFomatterAsset in PriceFomatterAsset.php



<?php

use Automattic\Jetpack\Constants;

class PriceFomatterAsset {
    /**
     * Constructor.
     */
    public function __construct() {
        add_action('init', [ $this, 'register_scripts']);
        add_action( 'wp_enqueue_scripts', [$this, 'enqueue_front_scripts' ]);
    }

    /**
     * Register all Dokan scripts and styles.
     *
     * @return void
     */
    public function register_scripts() {
        $suffix                   = Constants::is_true( 'SCRIPT_DEBUG' ) ? '' : '.min';
        $version                  = Constants::get_constant( 'WC_VERSION' );
        wp_register_script( 'accounting', WC()->plugin_url() . '/assets/js/accounting/accounting' . $suffix . '.js', array( 'jquery' ), '0.4.2', true );
        wp_register_script( 'wc-jquery-ui-touchpunch', WC()->plugin_url() . '/assets/js/jquery-ui-touch-punch/jquery-ui-touch-punch' . $suffix . '.js', array( 'jquery-ui-slider' ), $version, true );

        // Replace according to your plugin and js file location.
        wp_register_script( 'welabs_script_price_formatter', your-plugin-url . '/assets/frontend/js/price-formatter.js', array( 'jquery-ui-slider', 'wc-jquery-ui-touchpunch', 'accounting' ), null, true );
        wp_localize_script(
            'welabs_script_price_formatter',
            'welabs_price_formatter_params',
            array(
                'currency_format_num_decimals' => 2,
                'currency_format_symbol'       => get_woocommerce_currency_symbol(),
                'currency_format_decimal_sep'  => esc_attr( wc_get_price_decimal_separator() ),
                'currency_format_thousand_sep' => esc_attr( wc_get_price_thousand_separator() ),
                'currency_format'              => esc_attr( str_replace( array( '%1$s', '%2$s' ), array( '%s', '%v' ), get_woocommerce_price_format() ) ),
            )
        );
    }

    /**
     * Enqueue front-end scripts.
     *
     * @return void
     */
    public function enqueue_front_scripts() {
         // You may apply logic to enqueue this script like did_action.
         wp_enqueue_script( 'welabs_script_price_formatter' );
    }
}



Enter fullscreen mode Exit fullscreen mode

Now, let's create JS file named price-formatter.js where we will define a global function welabs_price_format to format the price according to Woocommerce settings.



window.welabs_price_format = function(price) {
    if ( typeof welabs_price_formatter_params === 'undefined' ) {
        return false;
    }

    return accounting.formatMoney( price, {
        symbol:    welabs_price_formatter_params.currency_format_symbol,
        decimal:   welabs_price_formatter_params.currency_format_decimal_sep,
        thousand:  welabs_price_formatter_params.currency_format_thousand_sep,
        precision: welabs_price_formatter_params.currency_format_num_decimals,
        format:    welabs_price_formatter_params.currency_format
    });
}



Enter fullscreen mode Exit fullscreen mode

Now, you have to instantiate the PriceFomatterAsset class. For example



 function load_price_formatter_asset() {
    new PriceFomatterAsset();
}

add_action( 'plugins_loaded', 'load_price_formatter_asset' );


Enter fullscreen mode Exit fullscreen mode

Now, You are ready to use welabs_price_format function in any javascript file.

Browser console

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs