php - Woocommerce- 使用 get_value 插入挂钩函数后结帐列上的空白内容
问题描述
我一直在尝试将此功能挂钩到 Woocommerce Checkout 页面的“订单挂钩”之一:
add_action( 'woocommerce_checkout_before_order_review', 'add_box_conditional' );
function add_box_conditional ( $checkout ) {
woocommerce_form_field( 'test', array(
'type' => 'checkbox',
'class' => array('test form-row-wide'),
'label' => __('conditional test'),
'placeholder' => __(''),
), $checkout->get_value( 'test' ));
}
如果我尝试在任何订单挂钩中获取自定义框的值,订单信息就会挂起并停止加载。我已经尝试过使用另一种类型的自定义字段,并且发生了同样的情况。
如果我在订单内容之外挂钩功能完美。自定义复选框将用于添加费用(验证后),因为它是我们商店的一个非常重要的选项,我希望它在订单详细信息中,因此它可以具有很强的焦点。有没有办法让函数在这些钩子上工作,或者我应该把它放在任何地方并用一个简单但不那么干净的 CSS 覆盖移动它?
解决方案
你不能仅仅获得这样的价值$checkout->get_value( 'test' ));
。挂钩woocommerce_checkout_create_order
并从 $_POST
那里获取价值。如果选中该复选框,则向订单添加自定义费用。
像这样:
function add_box_conditional() {
woocommerce_form_field( 'test', array(
'type' => 'checkbox',
'class' => array( 'test form-row-wide' ),
'label' => __( 'conditional test' ),
'placeholder' => __( '' ),
) );
}
add_action( 'woocommerce_checkout_before_order_review', 'add_box_conditional' );
function edit_order( $order, $data ) {
if( ! isset( $_POST[ 'test' ] ) ) {
return;
}
$checkbox_value = filter_var( $_POST[ 'test' ], FILTER_SANITIZE_NUMBER_INT );
if( $checkbox_value ){
$fee = 20;
$item = new \WC_Order_Item_Fee();
$item->set_props( array(
'name' => __( 'Custom fee', 'textdomain' ),
'tax_class' => 0,
'total' => $fee,
'total_tax' => 0,
'order_id' => $order->get_id(),
) );
$item->save();
$order->add_item( $item );
$order->calculate_totals();
}
}
add_action( 'woocommerce_checkout_create_order', 'edit_order', 10, 2 );
推荐阅读
- vba - VBA:为列中的重复值添加后缀
- django - 更改序列化 JSON 输出
- python - 从 C++ 向量到 Numpy ndarray 的转换非常慢
- javascript - recaptcha 在 Vue 组件中不起作用。当未加载 grecaptcha 时,grecaptcha.render 不是函数
- .net - Microsoft Bot builder : add pdf attachement and open it in web browser
- python - 在 Django 中为预注册用户创建用户帐户
- node.js - Nodejs - 所以当我尝试要求这些类时,我会出现一个奇怪的错误吗?
- url - wNumb 格式停止 noUiSlider 价格滑块工作
- c# - 新安装的 Visual Studio NuGet 包管理器无法导入 Microsoft.AspNetCore.All 包
- r - 将日期之间的值分配给 r 中的数据框