文章最后更新时间:
允许管理员后台修改用户名,
<?php
/*
Plugin Name: 修改用户名
Description: 允许管理员修改用户的用户名。
Version: 1.0
Author: 请教我阿祖
*/
if (!defined('ABSPATH')) {
exit; // 防止直接访问文件
}
// 添加管理菜单
function cu_add_admin_menu() {
add_menu_page(
'修改用户名', // 页面标题
'修改用户名', // 菜单标题
'manage_options', // 权限
'change-username', // 菜单slug
'cu_admin_page', // 回调函数
'dashicons-admin-users', // 图标
6 // 位置
);
}
add_action('admin_menu', 'cu_add_admin_menu');
// 管理页面内容
function cu_admin_page() {
if (!current_user_can('manage_options')) {
wp_die(__('你没有权限访问此页面。'));
}
if (isset($_POST['cu_change_username'])) {
$user_id = intval($_POST['cu_user_id']);
$new_username = sanitize_user($_POST['cu_new_username']);
if (empty($new_username)) {
echo '<div class="error"><p>请输入新的用户名。</p></div>';
} else {
$result = cu_change_username($user_id, $new_username);
if ($result === true) {
echo '<div class="updated"><p>用户名已成功修改。</p></div>';
} else {
echo '<div class="error"><p>' . esc_html($result) . '</p></div>';
}
}
}
$users = get_users(array('fields' => array('ID', 'user_login')));
?>
<div class="wrap">
<h1>修改用户名</h1>
<form method="post" action="">
<table class="form-table">
<tr>
<th scope="row"><label for="cu_user_id">选择用户</label></th>
<td>
<select name="cu_user_id" id="cu_user_id">
<?php foreach ($users as $user) : ?>
<option value="<?php echo esc_attr($user->ID); ?>"><?php echo esc_html($user->user_login); ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<th scope="row"><label for="cu_new_username">新用户名</label></th>
<td><input name="cu_new_username" type="text" id="cu_new_username" value="" class="regular-text"></td>
</tr>
</table>
<?php submit_button('修改用户名', 'primary', 'cu_change_username'); ?>
</form>
</div>
<?php
}
// 修改用户名的功能
function cu_change_username($user_id, $new_username) {
if (username_exists($new_username)) {
return '该用户名已被使用,请选择其他用户名。';
}
global $wpdb;
$result = $wpdb->update(
$wpdb->users,
array('user_login' => $new_username),
array('ID' => $user_id),
array('%s'),
array('%d')
);
if ($result === false) {
return '修改用户名时出错。';
}
// 清除缓存
clean_user_cache($user_id);
return true;
}

© 版权声明
THE END
暂无评论内容