为WordPress主题添加用户注册和登录功能,可以通过以下步骤进行操作:
functions.php
文件中添加以下代码,启用用户注册功能:// 启用用户注册功能
function custom_register_user() {
add_filter('wp_authenticate_user', 'custom_authenticate_user', 10, 2);
}
function custom_authenticate_user($user, $password) {
if (is_a($user, 'WP_User')) {
return $user;
}
$username = $user;
$email = $password;
if (empty($email)) {
$email = $username;
}
$password = wp_generate_password(6, false);
$user_id = wp_create_user($username, $password, $email);
if (is_wp_error($user_id)) {
return $user_id;
}
$user = get_user_by('id', $user_id);
return $user;
}
add_action('init', 'custom_register_user');
login.php
或page-login.php
)中添加以下代码,实现用户登录功能:<?php
// 登录功能
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['username']) && !empty($_POST['password'])) {
$credentials = [
'user_login' => $_POST['username'],
'user_password' => $_POST['password'],
'remember' => $_POST['rememberme']
];
$user = wp_signon($credentials, false);
if (is_wp_error($user)) {
echo '<p class="login-error">用户名或密码错误,请重试。</p>';
} else {
wp_redirect(home_url());
exit;
}
}
?>
<form class="login-form" action="<?php echo esc_url(home_url()); ?>/wp-login.php" method="post">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" name="username" id="username" required>
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" name="password" id="password" required>
</div>
<div class="form-group">
<label for="rememberme">
<input type="checkbox" name="rememberme" id="rememberme" value="forever">
记住我
</label>
</div>
<div class="form-group">
<input type="submit" class="btn-login" value="登录">
</div>
</form>
通过以上步骤,你就可以在WordPress主题中添加用户注册和登录功能。