Thêm mới, xóa, chỉnh sửa, tùy biến các trường dữ liệu trong trang Thanh toán WordPress (How to customize WooCommerce Checkout Fields)

Bạn đang sử dụng website WordPress và muốn tùy biến trang Thanh toán (Checkout) trong Woocommerce? Trong bài viết này, mình sẽ hướng dẫn bạn thực hiện điều đó. Bắt đầu nào.

Lưu ý: Bạn cần hiểu được cơ bản cách thêm code HTML, CSS và PHP trong WordPress trước khi đọc phần tiếp theo của bài viết nhé.

Bạn nào muốn tìm hiểu về việc tạo form chứa các trường dữ liệu Checkout thì có thể tham khảo bài viết Pre-Populate Checkout Form Fields Using URL Parameters của mình.

Cấu trúc HTML của trang Thanh toán Checkout

Bạn nắm cấu trúc HTML để có thể tùy biến CSS cơ bản

<body class="woocommerce-checkout">
<div class="woocommerce">
<form class="woocommerce-checkout">
<div id="customer_details" class="col2-set">
<div class="woocommerce-billing-fields">
<p class="form-row">
<div class="woocommerce-shipping-fields">
<p class="form-row">
<div class="woocommerce-additional-fields">
<div id="order_review" class="woocommerce-checkout-review-order">
<table class="woocommerce-checkout-review-order-table">
<div id="payment">
<ul class="wc_payment_methods payment_methods methods">
<div class="form-row place-order">

Danh sách các trường dữ liệu trong Checkout Field:

Bạn cần nắm được tên gọi của các trường dữ liệu để tùy biến:

  • Billing
    • billing_first_name
    • billing_last_name
    • billing_company
    • billing_address_1
    • billing_address_2
    • billing_city
    • billing_postcode
    • billing_country
    • billing_state
    • billing_email
    • billing_phone
  • Shipping
    • shipping_first_name
    • shipping_last_name
    • shipping_company
    • shipping_address_1
    • shipping_address_2
    • shipping_city
    • shipping_postcode
    • shipping_country
    • shipping_state
  • Account
    • account_username
    • account_password
    • account_password-2
  • Order
    • order_comments

Giá trị của các trường dữ liệu:

  • type – type of field (text, textarea, password, select)
  • label – label for the input field
  • placeholder – placeholder for the input
  • class – class for the input
  • required – true or false, whether or not the field is require
  • clear – true or false, applies a clear fix to the field/label
  • label_class – class for the label element
  • options – for select boxes, array of options (key => value pairs)

Trong trường hợp bạn muốn sử dụng woocommerce_default_address_fields filter. Filter này sẽ áp dụng cho cả billing và shipping:

  • country
  • first_name
  • last_name
  • company
  • address_1
  • address_2
  • city
  • state
  • postcode

Xóa 1 trường dữ liệu trong trang Thanh toán (Remove a checkout field)

Điều này khá đơn giản, nhưng hãy cẩn thận, vì thay đổi này có thể gây ra xung đột với các tiện ích mở rộng và plugin khác.

Bạn chọn tên checkout field muốn unset (muốn ẩn, xóa). Checkout field muốn giữ thì bạn thêm dấu // phía trước hoặc xóa dòng code unset đó đi. Bạn xem code và nhớ đọc 1 lưu ý quan trọng ngay phía dưới.

 /**
 Remove all possible fields
 **/
function wc_remove_checkout_fields( $fields ) {

    // Billing fields
    unset( $fields['billing']['billing_company'] );
    unset( $fields['billing']['billing_email'] );
    unset( $fields['billing']['billing_phone'] );
    unset( $fields['billing']['billing_state'] );
    unset( $fields['billing']['billing_first_name'] );
    unset( $fields['billing']['billing_last_name'] );
    unset( $fields['billing']['billing_address_1'] );
    unset( $fields['billing']['billing_address_2'] );
    unset( $fields['billing']['billing_city'] );
    unset( $fields['billing']['billing_postcode'] );

    // Shipping fields
    unset( $fields['shipping']['shipping_company'] );
    unset( $fields['shipping']['shipping_phone'] );
    unset( $fields['shipping']['shipping_state'] );
    unset( $fields['shipping']['shipping_first_name'] );
    unset( $fields['shipping']['shipping_last_name'] );
    unset( $fields['shipping']['shipping_address_1'] );
    unset( $fields['shipping']['shipping_address_2'] );
    unset( $fields['shipping']['shipping_city'] );
    unset( $fields['shipping']['shipping_postcode'] );

    // Order fields
    unset( $fields['order']['order_comments'] );

    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'wc_remove_checkout_fields' );

Lưu ý: Nếu bạn gặp lỗi “Xin hãy nhập một địa chỉ để tiếp tục” thì bạn có thể xem hướng dẫn sửa lỗi tại bài viết này.

Thay đổi trường dữ liệu từ bắt buộc sang KHÔNG BẮT BUỘC (Make a required field not required)

Đoạn code dưới đây sẽ minh họa cho trường dữ liệu Billing Phone

add_filter( 'woocommerce_billing_fields', 'wc_unrequire_wc_phone_field');
function wc_unrequire_wc_phone_field( $fields ) {
$fields['billing_phone']['required'] = false;
return $fields;
}

Giá trị false là không bắt buộc, nếu bạn muốn chuyển sang bắt buộc thì sửa thành true.

Thay đổi tên gọi và chú thích của trường dữ liệu (Change input field labels and placeholders)

Đoạn code như sau:

add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');
function custom_override_checkout_fields($fields)
 {
 unset($fields['billing']['billing_address_2']);
 $fields['billing']['billing_company']['placeholder'] = 'Business Name';
 $fields['billing']['billing_company']['label'] = 'Business Name';
 $fields['billing']['billing_first_name']['placeholder'] = 'First Name'; 
 $fields['shipping']['shipping_first_name']['placeholder'] = 'First Name';
 $fields['shipping']['shipping_last_name']['placeholder'] = 'Last Name';
 $fields['shipping']['shipping_company']['placeholder'] = 'Company Name'; 
 $fields['billing']['billing_last_name']['placeholder'] = 'Last Name';
 $fields['billing']['billing_email']['placeholder'] = 'Email Address ';
 $fields['billing']['billing_phone']['placeholder'] = 'Phone ';
 return $fields;
 }

Thêm 1 trường dữ liệu trong Billing và Shipping (Adding Custom Shipping And Billing Fields)

Bạn sử dụng hook woocommerce_checkout_fields để viết filter. Phương pháp này khác với bài viết trên BusinessBloomer website.

Đoạn code minh họa phía dưới áp dụng cho trường dữ liệu shipping_phone

// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function – $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
     $fields['shipping']['shipping_phone'] = array(
        'label'     => __('Phone', 'woocommerce'),
    'placeholder'   => _x('Phone', 'placeholder', 'woocommerce'),
    'required'  => false,
    'class'     => array('form-row-wide'),
    'clear'     => true
     );

     return $fields;
}

/**
 * Display field value on the order edit page
 */
 
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );

function my_custom_checkout_field_display_admin_order_meta($order){
    echo '<p><strong>'.__('Phone From Checkout Form').':</strong> ' . get_post_meta( $order->get_id(), '_shipping_phone', true ) . '</p>';
}

Kết quả như hình:

Thêm 1 trường dữ liệu lớn (Adding a Custom Special Field)

Đoạn code như sau:

/**
 * 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>';

}

Kết quả như hình:

Tiếp theo, bạn cần xác thực trường khi biểu mẫu thanh toán được đăng. Đối với ví dụ này, trường là bắt buộc và không phải là tùy chọn:

/**
 * Process the checkout
 */
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

function my_custom_checkout_field_process() {
    // Check if set, if its not set add an error.
    if ( ! $_POST['my_field_name'] )
        wc_add_notice( __( 'Please enter something into this new shiny field.' ), 'error' );
}

Lỗi thanh toán được hiển thị nếu trường dũ liệu mới để trống:

Cuối cùng, hãy lưu trường dữ liệu mới vào ĐƠN ĐẶT HÀNG ORDER bằng code sau:

/**
 * Update the order meta with field value
 */
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );

function my_custom_checkout_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['my_field_name'] ) ) {
        update_post_meta( $order_id, 'My Field', sanitize_text_field( $_POST['my_field_name'] ) );
    }
}

Thêm trường dữ liệu mới vào email (Adding Custom Fields To Emails)

Đoạn code minh họa:

/* To use: 
1. Add this snippet to your theme's functions.php file
2. Change the meta key names in the snippet
3. Create a custom field in the order post – e.g. key = "Tracking Code" value = abcdefg
4. When next updating the status, or during any other event which emails the user, they will see this field in their email
*/
add_filter('woocommerce_email_order_meta_keys', 'my_custom_order_meta_keys');

function my_custom_order_meta_keys( $keys ) {
     $keys[] = 'Tracking Code'; // This will look for a custom field called 'Tracking Code' and add it to emails
     return $keys;
}

0989 333 069
Chat Zalo