phpwordpresssession

How to start session safely in WordPress


I have referred this question: how to start session in wordpress.

With this code generated below critical issue.

<?php 
add_action('init', 'register_my_session');                                  

// session function                     
function register_my_session(){
    if( !session_id() ) {
        session_start();
    }
}

// calling session function                                 
register_my_session();                      
?>

How to start session safely in WordPress? I have tried to start the session but giving the critical error:

enter image description here


Solution

  • The critical issue is flagged by WordPress in there panel. If we use sessions in custom theme, then we need to only start it for frontend.

    So we need if(!is_admin()) to add before that hook.

    Try below snippet. It will resolve critical issues.

    functions.php

    <?php
    function register_my_session(){
      if( ! session_id() ) {
        session_start();
      }
    }
    if(!is_admin())
    {
      add_action('init', 'register_my_session');
    }
    ?>
    

    As per Question code we can see the issue.

    enter image description here

    After implemented code as per I suggested.

    enter image description here