【发布时间】:2021-01-07 19:07:36
【问题描述】:
我正在开发一个基于 wordpress 和 woocommerce 的网站,该网站提供与烹饪相关的培训信息并出售各种厨房材料。
想要参加培训的人请填写表格申请。厨房用品也通过 woocommerce 出售。
将培训添加到网站中,其中包含一种称为培训的内容。
要求通过 woocommerce 结构出售一些培训。但是,这些想要出售的“培训”希望以教育内容的形式保留。此外,请不要作为产品添加或移动。
首先,我创建了一个名为 Education 的虚拟产品。我把产品藏在商店里了。
然后我为教程添加了一个名为价格的自定义字段。将在此处输入要出售的每个培训的价格。
我在培训详细信息页面上有一个“注册培训”按钮,我将其更改为“购买”以获取想要出售的培训和链接
?add-to-cart=340&custom_price=600&quantity=1
我在表格中给出了。
这里340是我创建的虚拟产品的id。
单击“购买”按钮后,名为 Education 的虚拟产品将添加到购物篮中。但是我想根据打印的培训详细信息页面更新此培训的名称和价格。
我添加到functions.php的代码。
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals' );
function before_calculate_totals( $_cart ){
// loop through the cart_contents
foreach ( $_cart->cart_contents as $cart_item_key => &$item ) {
// you will need to determine the product id you want to modify, only when the "donation_amount" is passed
if ( $item['product_id'] == 340 && isset( $_GET['custom_price'] ) ){
// custom price from POST
$custom_price = $_GET['custom_price'] > 0 ? $_GET['custom_price'] : 0;
// save to the cart data
//$item['data']->price = $custom_price;
// new versions of WooCommerce may require (instead of line above)...
$item['data']->set_price($custom_price);
}
}
}
function ipe_product_custom_price( $cart_item_data, $product_id ) {
if( isset( $_POST['custom_price'] ) && !empty($_POST['custom_price'])) {
$cart_item_data[ "custom_price" ] = $_POST['custom_price'];
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'ipe_product_custom_price', 99, 2 );
我想用这些代码更新价格,但没有用。
如何动态更新虚拟商品的信息?或者你会建议什么不同的方法?
【问题讨论】:
标签: php wordpress woocommerce cart price