在WooCommerce结账页面添加自定义复选框,其值显示在管理订单中进行编辑。

5
我尝试添加一个 <input type="checkbox">,它的值也会显示在 WooCommerce 后端中,这样我就可以在最后看到顾客是否勾选了该框。

该复选框应该位于付款方式下方。

是否可能在 WooCommerce 结账时添加一个自定义复选框,其值在管理编辑订单中显示?


你目前尝试了什么?Stack Overflow不是一个代码编写服务,但如果你告诉我们你自己做了什么,我们可以帮助你解决关于你的代码的具体问题。请参阅如何提出好问题 - FluffyKitten
WooCommerce有一个教程涵盖了这个主题:使用操作和过滤器自定义结账字段 - Melebius
1个回答

26

您可以通过以下3个步骤完成:

  1. 在“付款方式”下方添加自定义复选框字段
  2. 保存订单元数据中被选中的自定义复选框字段
  3. 在订单编辑页面上勾选时显示自定义复选框字段

以下是相关代码:

// Add custom checkout field: woocommerce_review_order_before_submit
add_action( 'woocommerce_review_order_before_submit', 'my_custom_checkout_field' );
function my_custom_checkout_field() {
    echo '<div id="my_custom_checkout_field">';

    woocommerce_form_field( 'my_field_name', array(
        'type'      => 'checkbox',
        'class'     => array('input-checkbox'),
        'label'     => __('My custom checkbox'),
    ),  WC()->checkout->get_value( 'my_field_name' ) );
    echo '</div>';
}

// Save the custom checkout field in the order meta, when checkbox has been checked
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta', 10, 1 );
function custom_checkout_field_update_order_meta( $order_id ) {

    if ( ! empty( $_POST['my_field_name'] ) )
        update_post_meta( $order_id, 'my_field_name', $_POST['my_field_name'] );
}

// Display the custom field result on the order edit page (backend) when checkbox has been checked
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_custom_field_on_order_edit_pages', 10, 1 );
function display_custom_field_on_order_edit_pages( $order ){
    $my_field_name = get_post_meta( $order->get_id(), 'my_field_name', true );
    if( $my_field_name == 1 )
        echo '<p><strong>My custom field: </strong> <span style="color:red;">Is enabled</span></p>';
}

代码放在你正在使用的子主题(或主题)的function.php文件中,也可以放在任何插件文件中。

在WooCommerce 3+中测试并且有效。当复选框被选中时,在订单编辑页面下面显示自定义文本...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接