Currently I have some problems with cookies. I know the disadvantage of cookies, but I need to learn how to use it for an school assignment.

I need to make plugin for school with a button which set the post_title and post_id of the current post as an cookie.

What I’ve tried, and what is not working:

plugin.php:

<form method="POST" name="wishlist">
  <button type="submit" class="btn btn-default" name="submit_wishlist_post"><span class="glyphicon glyphicon-heart"></span> Add to your favorites</button>
  <br><br>
</form>

<?php 
  if ( isset ($_REQUEST[ 'submit_wishlist_post'])) {
   set_cookie_post();
  }
?>

single.php
I’m putting this on the top of the single.php file. Before the get_header();.

<?php 
 function set_cookie_post(){

  global $post;
  $cookie_name_post = $post->post_title;
  echo $cookie_name_post . '<br>';
  $cookie_value_post = $post->ID;
  echo $cookie_value_post . '<br>';

  setcookie($cookie_name_post, $cookie_value_post, time() + 86400 * 30, "/");
  wp_redirect($_SERVER['HTTP_REFERER']);
 }
?>

When I echo the variables $cookie_name_post and the $cookie_value_post, it’s echo-ing the correct value. Then I put these variables as the cookie name and value, and it isn’t working.

Also when I use the following code, the cookie will be set correct. But then I changed it to the post_title and post_id, and it isn’t working anymore…

<?php 
 function set_cookie_post(){

  $cookie_name_post = 'name';
  echo $cookie_name_post . '<br>';
  $cookie_value_post = 'value';
  echo $cookie_value_post . '<br>';

  setcookie($cookie_name_post, $cookie_value_post, time() + 86400 * 30, "/");
  wp_redirect($_SERVER['HTTP_REFERER']);
 }
?>

What am I doing wrong? Thanks in advance for the help and effort.

W. White

Read more here: Problem with the cookies


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: