javascript - 如何使用 $_SESSION 在 wordpress 上更改登录到注销按钮?
问题描述
所以我在 Wordpress 上有一个自定义登录页面,它连接到我的用户数据库并检查所有信息是否正确。这是 login.php:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['email'])){
// removes backslashes
$email = stripslashes($_REQUEST['email']);
//escapes special characters in a string
$email = mysqli_real_escape_string($conn,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($conn,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE email='$email'
and password='".md5($password)."'";
$result = mysqli_query($conn,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $email;
// Redirect user to index.php
header("Location: index.php");
}else{
echo "<div class='form'>
<h3>Email/password is incorrect.</h3>
<br/>Click here to <a href='../login/'>Login</a></div>";
}
}else{
?>
<div class="form">
<!-- <h1>Log In</h1> -->
<form action="" method="post" name="login">
<input type="text" name="email" placeholder="Email" required />
<input type="password" name="password" placeholder="Password" required />
<br>
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='../register/'>Register Here</a></p>
</div>
<?php } ?>
</body>
</html>
我想要做的是在用户登录后将我的 Wordpress 标题上的 LOGIN 按钮更改为 LOGOUT (并在可能的情况下显示用户信息),我想我可以使用该$_SESSION['email'] = $email;
变量来做到这一点。
我怎样才能做到这一点?
非常感谢!
解决方案
您可以使用内置的 WordPress 函数 is_user_logged_in() 还是使用数据库中的自定义表而不是 WordPress 用户表 wp_user 登录?
<?php
if ( is_user_logged_in() ) {
echo '<a href="../wp-login.php?action=logout">Login out</a>';
} else {
echo '<a href="../login/">Login</a>';
}
?>
如果您的登录系统独立于 WordPress,您需要检查您的登录功能并查看它创建了哪些会话变量,您可能还需要自己启动会话,如果它不在这样的函数中,那么
session_start();
if (isset($_SESSION['email'])) {
/// your login button code here
} else {
/// your logout button code here
}
将其添加到您的 wordpress 菜单中的功能,您需要对其进行样式设置:
add_filter('wp_nav_menu_items', 'button_login_logout', 10, 2);
function button_login_logout() {
ob_start();
if (isset($_SESSION['email'])) :
?>
<a role="button" href="logoutlink">Log Out</a>.
<?php
else :
?>
<a role="button" href="loginlink">Log In</a>
<?php
endif;
return ob_get_clean();
}
推荐阅读
- bash - 从标准输入读取变量时如何在 bash 中使用 GNU 并行?
- google-sheets - 根据入住和退房时间谷歌表格查找给定时间的总数
- paypal - 从旧的 PayPal 按钮过渡到 PayPal Javascript SDK 按钮
- javascript - 当托管在与应用程序本身不同的域上时,如何为 Web 组件获取 HTML 和 CSS 文件?
- python - 我不知道如何在函数中循环两次以修改列表
- list - 一个 2 元组整数列表有多少种方法可以组合成一个完整整数范围的有序元组?
- javascript - 如何在 Mapbox GL JS 中使用私有 Mapbox Tileset?
- xml - Xpath 查找两个属性匹配的以下兄弟姐妹
- vb.net - VB.Net以日期格式查找月份的最后一天
- r - 获取 Google 搜索结果编号