问题描述
我正在寻找一种基于其他输入将数据保存到数据库的方法,我有一个 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
。现在我有点困惑,有两个问题:
- 我应该创建一个新的
woocommerce_wp_text_input
并将其隐藏吗? - 是否可以在不创建
$calculation
的情况下将woocommerce_wp_text_input
的结果保存到数据库中?
解决方法
是的,这是可能的:您可以在 WC_Data
对象上使用 update_meta_data()
方法 save()
和 WC_Product
添加自定义字段。
您只需要在该自定义字段的元键下定义即可。
在下面的代码中,将 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