php 使注册字段usermeta值为WooCommerce中的每个用户唯一

3phpmpom  于 11个月前  发布在  PHP
关注(0)|答案(1)|浏览(127)

我试图验证WooCommerce注册表单中每个用户的唯一值的公司名称字段,但我遇到了麻烦:

// That's what I got, but it doesn't work...
add_action( 'woocommerce_created_customer', 'custom_billing_company_validation');
function custom__billing_company_validation( $data, $errors ) {

    $billing_company = isset( $data['billing_company'] ) ? sanitize_text_field( $data['billing_company'] ) : '';

    if ( ! empty( $billing_company ) ) {

        global $wpdb;

        $count =$wpdb->get_row("SELECT 1 FROM $wpdb->usermeta WHERE
       $wpdb->usermeta.meta_key = 'billing_company' AND $wpdb->usermeta.meta_value = '$billing_company'  AND  $wpdb->usermeta.user_id != $user->ID"); 

        if ( $count > 0 ) {
            $errors->add( 'validation', __('The "Name Company " already exists, please contact us.') );
        }
    }

}

字符串

6mzjoqzu

6mzjoqzu1#

**更新2:**下面我使用了一个通用函数来检查是否存在一些用户元数据。在现有代码中添加此函数:

// Conditional utility function
function user_meta_field_value_exists( $meta_key, $meta_value ) {
    global $wpdb;
    $result = $wpdb->get_col( $wpdb->prepare( "
        SELECT um.user_id FROM {$wpdb->prefix}usermeta um
        WHERE um.meta_key = '%s' AND um.meta_value LIKE '%s'
    ", $meta_key, $meta_value ) );
    return empty($result) ? false : true;
}

字符串
然后从显示或隐藏WooCommerce注册字段基于选定的字段值答案代码,替换account_registration_field_validation()函数如下:

// registration Field validation
add_filter( 'woocommerce_registration_errors', 'account_registration_field_validation', 10, 3 );
function account_registration_field_validation( $errors, $username, $email ) {
    if ( $_POST['role'] === 'customer' && isset($_POST['billing_company']) ) {
        if ( empty($_POST['billing_company']) ) {
            $errors->add( 'billing_company_error', __( 'Name Company is a required field', 'woocommerce' ) );
        } elseif ( ! empty($_POST['billing_company']) &&
        user_meta_field_value_exists( 'billing_company', sanitize_text_field($_POST['billing_company']) ) ) {
            $errors->add( 'billing_company_error', __( 'The "Name Company" already exists, please contact us.', 'woocommerce' ) );
        }
    } 
    if ( $_POST['role'] === 'subscriber' && isset($_POST['billing_product']) && empty($_POST['billing_product']) ) {
        $errors->add( 'billing_product_error', __( 'Company Product is a required field', 'woocommerce' ) );
    }
    return $errors;
}


代码放在你的子主题的functions.php文件中(或插件中)。测试和工作。


的数据

相关问题