skip to Main Content

I am working on a WordPress plugin that has two pages (index and settings). I am not quite sure how to handle the settings here but I think the plugin is too simple to use a table to store the data in a database.

The index page has an editor that should use the cookies/session variables from settings.

With that said, I am not managing to store the settings data in session or cookies:

Whenever I use $_SESSION['timeout'] = 8000; it gets wiped when refreshing the current page.

This is my settings page PHP code:

<?php
wp_enqueue_style('phpp-css', plugins_url('css/style.css', dirname(__FILE__)));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_SESSION['theme'] = sanitize_text_field($_POST['theme']);
    $_SESSION['timeout'] = floatval(sanitize_text_field($_POST['timeout']));
}

$theme = $_SESSION['theme'] ?? 'twilight';
$timeout = $_SESSION['timeout'] ?? 8000;
?>

So, $theme and $timeout exist only after the form is submitted. But, by the time I refresh the page both variables have the default information and $_SESSION is NULL.

I also attempted another approach that is using cookies:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    setcookie('theme', sanitize_text_field($_POST['theme']));
    setcookie('timeout', floatval(sanitize_text_field($_POST['timeout'])));
}

But I get the headers already sent warning:

Warning: Cannot modify header information – headers already sent by (output started at…

So, I am not quite sure how should I stablish the settings interconnection between the index and the settings page without having to store them within the database. Any suggestions?

2

Answers


  1. Chosen as BEST ANSWER

    I actually solved this by using instead JavaScript cookies.

    The cookies.js:

    function setCookie(name,value,days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "")  + expires + "; path=/";
    }
    
    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
    
    function eraseCookie(name) {   
        document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }
    

    The settings.php:

    document.getElementById('settings-form').addEventListener('submit', e => {
            const theme = e.target.theme.value;
            const timeout = e.target.timeout.value;
    
            setCookie('theme', theme, 7);
            setCookie('timeout', timeout, 7);
        })
    

    The index.php:

    document.addEventListener("DOMContentLoaded", () => {
            const theme = getCookie('theme');
    
            const element = document.querySelector("#editor")
            const editor = ace.edit(element)
    
            editor.setTheme(`ace/theme/${theme}`)
    
    });
    

  2. I think you can use PHP COOKIE and set an expiration date Or you could use wp transients, which are expirable too. But if you want to Make it permanently save feel free to use options API.

    https://www.w3schools.com/php/php_cookies.asp

    https://developer.wordpress.org/apis/transients

    https://developer.wordpress.org/apis/options

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search