如何使公司名称字段中的值对于每个用户都是唯一的

问题描述 投票:0回答:1

我正在尝试验证 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.') );
        }
    }

}
php wordpress woocommerce registration usermetadata
1个回答
0
投票

下面我使用一个通用函数来检查一些用户元数据是否存在。 尝试以下操作:

// 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;
}

// Check that the billing company doesn't exist yet
add_action( 'woocommerce_created_customer', 'custom_billing_company_validation');
function custom__billing_company_validation( $data, $errors ) {
    $meta_key   = 'billing_company';
    $meta_value = isset($data[$meta_key]) ? sanitize_text_field($data[$meta_key]) : '';

    if ( empty( $meta_value ) ) {
        $meta_value = isset($_POST[$meta_key]) ? sanitize_text_field($_POST[$meta_key]) : '';
    }

    if ( ! empty( $meta_value ) && user_meta_field_value_exists( $meta_key, $meta_value ) ) {
        $errors->add( 'validation', __('The "Name Company " already exists, please contact us.', 'woocommerce') );
    }
}

代码位于子主题的functions.php 文件中(或插件中)。应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.