首页 > 解决方案 > 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 覆盖移动它?

标签: phpwordpresswoocommercehookhook-woocommerce

解决方案


你不能仅仅获得这样的价值$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 );

推荐阅读