Search code examples
phpwordpresshttp-redirectheader

Having Issue on Redirecting With Session in WordPress


I am trying to create a simple login system in WordPress using core PHP but I am getting this error message

Warning: Cannot modify header information - headers already sent by (output started at /www/www/www/wp-content/themes/mytheme/header.php:20) in /www/www/www/wp-content/themes/mytheme/page-solutions.php on line 9

In the header.php template I have

<?php
session_start();
/**
 * The header.
 *
 */
?>
<!doctype html>
<html lang="en">
<head>
...

and in the page-solutions.php page

<?php
/**
 * Template Name: Solutions
 *
 */
get_header();

if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: home");
exit;
}

As you can see I am trying to redirect not logged users to front-page.php which I called it Home but I am getting error on header("location: home"); Can you please let me know how to fix this?


Solution

  • Functions that modifies headers must be called before any output is made. In this case you're calling get_header() functions which sends an output, and then youre trying to modify the header. Try changing the order that you execute the code, like this:

    <?php
    /**
    * Template Name: Solutions
    *
    */
    
     if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
     header("location: home");
     exit;
     }
    
     get_header();