是否有可能制定自定义价格?

我在 Wordpress 上通过 WooCommerce 销售礼品卡。我的客户应该能够自己设置礼品卡金额的值。我只能通过插件来做到这一点。是否有可能通过更改一些代码或通过functions.php 来做到这一点?

已安装 Pimwick 礼品卡 Pro


忽然笑
浏览 115回答 1
1回答

饮歌长啸

是的,但如果从没有额外插件的全新 WooCommerce 安装中执行此操作,这是一个相当复杂的过程。你需要做以下事情来实现它:为产品添加自定义输入字段以添加自定义价格将该产品添加到购物车时,将自定义输入字段中的数据保存到会话(购物车)创建订单时,将购物车元数据(上面在 #2 中创建)添加到订单中根据自定义价格元调整产品的成本(在上面的 #3 中添加)。第 1 步:添加自定义输入字段:您可以使用woocommerce_before_add_to_cart_button过滤器添加输入字段,如下所示。或者,您可以使用woocommerce_wp_text_input-这是一个示例。add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_price_input', 100 );function add_custom_price_input() {&nbsp; &nbsp; if(get_the_ID() != 123) { //use the product ID of your gift card here, otherwise all products will get this additional field&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; echo '<input type="number" min="50" placeholder="50" name="so_57140247_price">';}第 2 步:将自定义价格保存到购物车/会话接下来,我们需要确保您的自定义输入字段数据被转移到购物车/会话数据。我们可以使用woocommerce_add_cart_item_data&nbsp;(&nbsp;docs&nbsp;|&nbsp;example&nbsp;)过滤器:add_filter( 'woocommerce_add_cart_item_data', 'add_custom_meta_to_cart', 10, 3 );function add_custom_meta_to_cart( $cart_item_data, $product_id, $variation_id ) {&nbsp; &nbsp; $custom_price&nbsp; &nbsp;= intval(filter_input( INPUT_POST, 'so_57140247_price' ));&nbsp; &nbsp; if ( !empty( $custom_price ) && $product_id == 123 ) { //check that the custom_price variable is set, and that the product is your gift card&nbsp; &nbsp; &nbsp; &nbsp; $cart_item_data['so_57140247_price'] = $custom_price; //this will add your custom price data to the cart item data&nbsp; &nbsp; }&nbsp; &nbsp; return $cart_item_data;}第 3 步:将购物车元添加到订单中接下来,我们必须将购物车/会话中的元添加到订单本身,以便它可以用于订单总额计算。我们使用woocommerce_checkout_create_order_line_item&nbsp;(&nbsp;docs&nbsp;|&nbsp;example&nbsp;)来做到这一点:add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_meta_to_order', 10, 4 );function add_custom_meta_to_order( $item, $cart_item_key, $values, $order ) {&nbsp; &nbsp; //check if our custom meta was set on the line item of inside the cart/session&nbsp; &nbsp; if ( !empty( $values['so_57140247_price'] ) ) {&nbsp; &nbsp; &nbsp; &nbsp; $item->add_meta_data( '_custom_price', $values['so_57140247_price'] ); //add the value to order line item&nbsp; &nbsp; }&nbsp; &nbsp; return;}第 4 步:调整礼品卡订单项的总数最后,我们根据输入字段中输入的值简单地调整礼品卡行项目的成本。我们可以挂钩woocommerce_before_calculate_totals&nbsp;(docs&nbsp;|&nbsp;example)来做到这一点。add_action( 'woocommerce_before_calculate_totals', 'calculate_cost_custom', 10, 1);function calculate_cost_custom( $cart_obj ) {&nbsp; &nbsp; foreach ( $cart_obj->get_cart() as $key => $value ) {&nbsp; &nbsp; &nbsp; &nbsp; $price&nbsp; &nbsp; &nbsp; = intval($value['_custom_price']);&nbsp; &nbsp; &nbsp; &nbsp; $value['data']->set_price( $price );&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP