【发布时间】:2019-07-22 06:27:46
【问题描述】:
我正在 Wordpress 上通过 WooCommerce 销售礼品卡。我的客户应该能够自己设置礼品卡金额的值。我只是能够通过插件做到这一点。是否有可能通过更改一些代码或通过functions.php来做到这一点?
已安装 Pimwick 礼品卡专业版
【问题讨论】:
标签: php wordpress woocommerce
我正在 Wordpress 上通过 WooCommerce 销售礼品卡。我的客户应该能够自己设置礼品卡金额的值。我只是能够通过插件做到这一点。是否有可能通过更改一些代码或通过functions.php来做到这一点?
已安装 Pimwick 礼品卡专业版
【问题讨论】:
标签: php wordpress woocommerce
是的,但是如果从完全全新的 WooCommerce 安装中执行此操作而没有额外的插件,这是一个相当复杂的过程。你需要做以下事情来实现它:
您可以使用woocommerce_before_add_to_cart_button 过滤器添加输入字段,如下所示。
您也可以使用woocommerce_wp_text_input - here's an example。
add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_price_input', 100 );
function add_custom_price_input() {
if(get_the_ID() != 123) { //use the product ID of your gift card here, otherwise all products will get this additional field
return;
}
echo '<input type="number" min="50" placeholder="50" name="so_57140247_price">';
}
接下来,我们需要确保将您的自定义输入字段数据转移到购物车/会话数据中。我们可以使用woocommerce_add_cart_item_data ( docs | example ) 过滤器:
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 ) {
$custom_price = intval(filter_input( INPUT_POST, 'so_57140247_price' ));
if ( !empty( $custom_price ) && $product_id == 123 ) { //check that the custom_price variable is set, and that the product is your gift card
$cart_item_data['so_57140247_price'] = $custom_price; //this will add your custom price data to the cart item data
}
return $cart_item_data;
}
接下来,我们必须将购物车/会话中的元数据添加到订单本身,以便可以在订单总额计算中使用它。我们使用woocommerce_checkout_create_order_line_item ( docs | example ) 来做到这一点:
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 ) {
//check if our custom meta was set on the line item of inside the cart/session
if ( !empty( $values['so_57140247_price'] ) ) {
$item->add_meta_data( '_custom_price', $values['so_57140247_price'] ); //add the value to order line item
}
return;
}
最后,我们简单地根据输入字段中输入的值调整礼品卡行项目的成本。我们可以连接到woocommerce_before_calculate_totals ( docs | example ) 来做到这一点。
add_action( 'woocommerce_before_calculate_totals', 'calculate_cost_custom', 10, 1);
function calculate_cost_custom( $cart_obj ) {
foreach ( $cart_obj->get_cart() as $key => $value ) {
$price = intval($value['_custom_price']);
$value['data']->set_price( $price );
}
}
【讨论】: