php - Save WooCommerce product data to database based on other inputs calculation
Get the solution ↓↓↓I am looking for a way to save data to a database base on other inputs, I have awoocommerce_wp_text_input
and I use it to calculate the price per unit:
I usewoocommerce_wp_text_input( $ppuvnumber );
for getting the net weight (without packaging) and I useget_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 asmeta_key
. Now I am a little bit confuse and have two questions:
- Should I create a new
woocommerce_wp_text_input
and hide it? - Is it possible to save the result of
$calculation
to database without creatingwoocommerce_wp_text_input
?
Answer
Solution:
Yes it's possible: You can use theWC_Data
methodsupdate_meta_data()
andsave()
on theWC_Product
object to add a custom field.
You just need to define under what meta key for that custom field.
On the code below replacesome_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 WordPressupdate_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
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: composer detected issues in your platform: your composer dependencies require a php version ">= 8.0.2".
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.