Sim*_*ory 2 php wordpress checkout woocommerce hook-woocommerce
我可以在WooCommerce结帐屏幕上添加一组自定义字段,但需要将其移至“结算明细”上方。
那怎么办?
根据WooCommerce官方文档,这是添加额外的自定义结帐字段的示例代码:
/**
* Add the field to the checkout
*/
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );
function my_custom_checkout_field( $checkout ) {
echo '<div id="my_custom_checkout_field"><h2>' . __('My Field') . '</h2>';
woocommerce_form_field( 'my_field_name', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('Fill in this field'),
'placeholder' => __('Enter something'),
), $checkout->get_value( 'my_field_name' ));
echo '</div>';
}
Run Code Online (Sandbox Code Playgroud)
已更新:结帐计费字段之前只有一个可用的钩子,可用于在结帐表单中添加自定义字段。试试这个完整的代码:
add_action( 'woocommerce_checkout_before_customer_details', 'custom_checkout_fields_before_billing_details', 20 );
function custom_checkout_fields_before_billing_details(){
$domain = 'woocommerce';
$checkout = WC()->checkout;
echo '<div id="my_custom_checkout_field">';
echo '<h3>' . __('My New Fields Section') . '</h3>';
woocommerce_form_field( '_my_field_name', array(
'type' => 'text',
'label' => __('My 1st new field', $domain ),
'placeholder' => __('Please fill in "my 1st new field"', $domain ),
'class' => array('my-field-class form-row-wide'),
'required' => true, // or false
), $checkout->get_value( '_my_field_name' ) );
echo '</div>';
}
// Custom checkout fields validation
add_action( 'woocommerce_checkout_process', 'custom_checkout_field_process' );
function custom_checkout_field_process() {
if ( isset($_POST['_my_field_name']) && empty($_POST['_my_field_name']) )
wc_add_notice( __( 'Please fill in "My 1st new field".' ), 'error' );
}
// Save custom checkout fields the data to the order
add_action( 'woocommerce_checkout_create_order', 'custom_checkout_field_update_meta', 10, 2 );
function custom_checkout_field_update_meta( $order, $data ){
if( isset($_POST['_my_field_name']) && ! empty($_POST['_my_field_name']) )
$order->update_meta_data( '_my_field_name', sanitize_text_field( $_POST['_my_field_name'] ) );
}
Run Code Online (Sandbox Code Playgroud)
代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试和工作。
您将获得一个带有新的自定义字段的新字段部分(在该字段中,您还可以拥有许多字段):
官方参考文档:使用操作和过滤器自定义结帐字段