Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Woocommerce product sold in units of gram

I would like to create a product in WooCommerce that is sold in units of gram.

The customer would enter the number of grams they want (in an input field) on the product page, and the price would be computed on the fly and added to the cart.

My question is: is this possible, and if so, can someone give me just a "big picture" idea of how I would implement it?

I don't need line-by-line code, just hoping someone with more knowledge of the structure of Woo can guide me on how to best attack the problem.

I already have parts of it worked out:

  • I can decide that the price entered for the product is the price per 100 grams, so that is how the seller will enter the price.

  • Then I can write a little bit of Javascript to compute the price on the fly and display it on the page as the user types the amount they want. No problem.

But... I think every discrete product in Woo needs to have its own price.. So for example, if a customer wants 123g of a product, it seems like I might have to create a variation on the fly for that specific price/amount, and then add that to the cart. Which (judging by this) looks non-trivial and a little hacky. Is there a better way to do this?

like image 228
Eric Avatar asked Nov 25 '25 17:11

Eric


2 Answers

WooCommerce has an option to show the weights as grams.

enter image description here

The following code will display the KG weights as grams on the WooCommerce templates :



    // Convert the product weight
       function ag_woocommerce_product_get_weight( $weight ) {

       // Only convert if we have a weight
    if ($weight) {

    // The weight is in KGS, and we want grams, to multiple by 1000
    $weight = $weight * 1000;
    }

    return $weight;
    };
    // add the filter
    add_filter( 'woocommerce_product_get_weight', 'ag_woocommerce_product_get_weight', 10, 1 );

Hope this might help. Cheers!

like image 151
Vikas Yadav Avatar answered Nov 28 '25 11:11

Vikas Yadav


There is a free plugin for WooCommerce that allows you to input a unit of measure (UOM) for each product:

https://wordpress.org/plugins/woocommerce-unit-of-measure/

like image 20
Michael Yaeger Avatar answered Nov 28 '25 11:11

Michael Yaeger