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
I actually solved this by using instead JavaScript cookies.
The
cookies.js
:The
settings.php
:The
index.php
: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