【问题标题】:Alphabet characters only for billing and shipping names in WooCommerce字母字符仅用于 WooCommerce 中的计费和运输名称
【发布时间】:2017-08-08 09:28:56
【问题描述】:

如何在 WooCommerce 结帐中仅限制账单名字、账单姓氏、送货名字和送货姓氏中的字母字符?

我正在我的子主题的 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'
        )
    );
}

【问题讨论】:

  • 函数结束时不应该return $fields;吗?
  • 你能告诉我正确的位置和语法吗?
  • return $fields 放在custom_override_checkout_fields 函数的最后一个右大括号之前。

标签: php wordpress validation woocommerce checkout


【解决方案1】:

您可以通过在服务器端验证结帐表单提交来做到这一点 使用 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 文件中。
代码已经过测试并且可以工作。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 2022-06-30
    • 2021-09-08
    • 2018-09-04
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多