首页 > 解决方案 > 如何使用 $_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;变量来做到这一点。

我怎样才能做到这一点?

非常感谢!

标签: javascriptphphtmlcsswordpress

解决方案


您可以使用内置的 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();
}

推荐阅读