Skip to content
Advertisement

Save WooCommerce product data to database based on other inputs calculation

I am looking for a way to save data to a database base on other inputs, I have a woocommerce_wp_text_input and I use it to calculate the price per unit:

I use woocommerce_wp_text_input( $ppuvnumber ); for getting the net weight (without packaging) and I use get_price(); for price. Then I use this formula to calculate the price per unit:

$product_att = wc_get_product ( $post->ID );    
$price_to_use = $product_att->get_price();
$amount_to_use = $product_att->get_meta( 'rasa_store_product_ppu_number' );
$calculation = round( $price_to_use/$amount_to_use, 2) ;

I want to save the amount of $calculation to database as meta_key . Now I am a little bit confuse and have two questions:

  1. Should I create a new woocommerce_wp_text_input and hide it?
  2. Is it possible to save the result of $calculation to database without creating woocommerce_wp_text_input?

Advertisement

Answer

Yes it’s possible: You can use the WC_Data methods update_meta_data() and save() on the WC_Product object to add a custom field.

You just need to define under what meta key for that custom field.

On the code below replace some_meta_key by the desired meta key:

$product     = wc_get_product( $post->ID ); // get the product Object
$price       = $product->get_price(); // The product price
$ppu_number  = $product->get_meta( 'rasa_store_product_ppu_number' ); // Get some custom meta data
$calculation = round( $price/$ppu_number, 2) ; // Make the calculation

$product->update_meta_data('some_meta_key', $calculation); // Set the calculation as a new custom meta data
$product->save(); // Save to database

It should work.

You can also use WordPress update_post_meta() as follows (the old way):

$product     = wc_get_product( $post->ID ); // get the product Object
$price       = $product->get_price(); // The product price
$ppu_number  = $product->get_meta( 'rasa_store_product_ppu_number' ); // Get some custom meta data
$calculation = round( $price/$ppu_number, 2) ; // Make the calculation

update_post_meta( get_the_ID(), 'some_meta_key', $calculation ); // Set and save the calculation as a new custom meta data
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement