簡體   English   中英

字母字符僅用於WooCommerce中的結算和發貨名稱

[英]Alphabet characters only for billing and shipping names in WooCommerce

如何在WooCommerce結帳中僅限制結算名,賬單姓,發貨名和運送姓的字母字符?

我正在我的Child Theme的functions.php文件中嘗試以下操作,這導致我在WooCommerce結帳時沒有顯示結帳部分。 請指教。

add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');

function custom_override_checkout_fields($fields) {
    $fields['billing']['billing_first_name'] = array(
        'label' => __('First name', 'woocommerce'),
        'placeholder' => _x('First name', 'placeholder', 'woocommerce'),
        'required' => false,
        'clear' => false,
        'type' => 'text',
        'class' => array(
            'alpha'
        )
    );
}

您可以通過使用woocommerce_checkout_process掛鈎和PHP ctype_alpha()函數驗證服務器端的結帳表單提交來完成此操作。

這是代碼:

add_action('woocommerce_checkout_process', 'wh_alphaCheckCheckoutFields');

function wh_alphaCheckCheckoutFields() {
    $billing_first_name = filter_input(INPUT_POST, 'billing_first_name');
    $billing_last_name = filter_input(INPUT_POST, 'billing_last_name');
    $shipping_first_name = filter_input(INPUT_POST, 'shipping_first_name');
    $shipping_last_name = filter_input(INPUT_POST, 'shipping_last_name');
    $ship_to_different_address = filter_input(INPUT_POST, 'ship_to_different_address');

    if (empty(trim($billing_first_name)) || !ctype_alpha($billing_first_name)) {
        wc_add_notice(__('Only alphabets are alowed in <strong>Billing First Name</strong>.'), 'error');
    }
    if (empty(trim($billing_last_name)) || !ctype_alpha($billing_last_name)) {
        wc_add_notice(__('Only alphabets are alowed in <strong>Billing Last Name</strong>.'), 'error');
    }
    // Check if Ship to a different address is set, if it's set then validate shipping fields.
    if (!empty($ship_to_different_address)) {
        if (empty(trim($shipping_first_name)) || !ctype_alpha($shipping_first_name)) {
            wc_add_notice(__('Only alphabets are alowed in <strong>Shipping First Name</strong>.'), 'error');
        }
        if (empty(trim($shipping_last_name)) || !ctype_alpha($shipping_last_name)) {
            wc_add_notice(__('Only alphabets are alowed in <strong>Shipping Last Name</strong>.'), 'error');
        }
    }
}

代碼位於活動子主題(或主題)的functions.php文件中。 或者也可以在任何插件PHP文件中。
代碼經過測試和運行。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM