根据其他输入计算将 WooCommerce 产品数据保存到数据库

Save WooCommerce product data to database based on other inputs calculation

我正在寻找一种基于其他输入将数据保存到数据库的方法,我有一个 woocommerce_wp_text_input 并用它来计算单位价格:

我使用 woocommerce_wp_text_input( $ppuvnumber ); 获取净重(不含包装),我使用 get_price(); 获取价格。然后我用这个公式来计算单价:

$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) ;

我想将 $calculation 的金额作为 meta_key 保存到数据库中。 现在我有点困惑,有两个问题:

  1. 我应该创建一个新的 woocommerce_wp_text_input 并隐藏它吗?
  2. 是否可以在不创建 woocommerce_wp_text_input 的情况下将 $calculation 的结果保存到数据库?

是的,这是可能的:您可以在 WC_Product 对象上使用 WC_Data 方法 update_meta_data()save() 来添加自定义字段。

您只需在该自定义字段的元键下定义。

在下面的代码中用所需的元键替换 some_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

应该可以。

您也可以使用 WordPress update_post_meta() 如下 (旧方法):

$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