Saving and Retrieving cookie value in WordPress


I tried this code snippet in WordPress.

If you open the URL like this (It’s showing the text Hello wherever the shortcode is [text] is mentioned)

But if you open the URL without the /?text=Hello in the URL it’s not getting the data from the cookie and nothing appears. The Cookie is getting saved in the Browser.

It’s working normally, But with WordPress not working.

if (empty($_GET['text'])) {
   $text = $_COOKIE["text"];
} elseif (isset($_GET['text'])) {
   $text = $_GET['text'];
   setcookie("text", "$text", time()+30*24*60*60, '/');

function printtext(){
    global $text;
    return $text;
add_shortcode('text', 'printtext'); 

MC Naveen 4 months 0 Answers 19 views 0

Leave an answer