您可以使用sql查询检查重复的用户元。在下面的代码中,如果发现其他用户的重复记录,则会显示错误消息,而不会更新值。在活动主题的函数中添加以下代码。php文件。
function save_cust_user_profile_fields( $user_id ) {
if ( isset($_POST[\'social_number\']) ) {
global $wpdb;
$social_number = $_POST[\'social_number\'];
# query to check duplicate value
$query = "SELECT $wpdb->users.ID FROM $wpdb->users INNER JOIN $wpdb->usermeta ON ( $wpdb->users.ID = $wpdb->usermeta.user_id ) INNER JOIN $wpdb->usermeta AS mt1 ON ( $wpdb->users.ID = mt1.user_id ) WHERE 1=1 AND
( $wpdb->usermeta.meta_key = \'social_number\' AND $wpdb->usermeta.meta_value = $social_number ) ";
$result = $wpdb->get_results($query);
#if result found then redirect with error msg
if($result && $user_id != $result[0]->ID){
add_filter( \'wp_redirect\', \'add_notice_query_variable\', 99 );
}
else
{
# if not found duplicate then update
update_user_meta( $user_id, \'social_number\', intval($_POST[\'social_number\']));
}
}
}
add_action( \'personal_options_update\', \'save_cust_user_profile_fields\' );
add_action( \'edit_user_profile_update\', \'save_cust_user_profile_fields\' );
#Add query var in url for display error message
function add_notice_query_variable( $location ) {
remove_filter( \'wp_redirect\', \'add_notice_query_variable\' , 99 );
return add_query_arg( array( \'social_number\' => $_POST[\'social_number\'] ), $location );
}
# display duplicate error admin notice
add_action( \'admin_notices\', \'admin_notices_callback\');
function admin_notices_callback() {
if ( ! isset( $_GET[\'social_number\'] )) {
return;
}
?>
<div class="error notice">
<p><?php esc_html_e( \'social_number : \'.$_GET[\'social_number\'].\' already used in other user, Please try different!\', \'\' ); ?></p>
</div>
<?php
}
我已经测试过了,对我来说效果很好。
https://prnt.sc/rau4ug 如果这对你有用,请告诉我。