我制作了一个最喜欢的插件。通过一个快捷码,我可以在任何我想要的地方显示“愿望/收藏夹列表”的按钮。此按钮用于在cookie数组中添加页面/帖子/博客/文章等的post\\u id,代码如下:
<?php
if (isset($_POST[\'submit_wishlist\'])){
if (!isset($_COOKIE[\'favorites\'])){
//echo \'not set <br>\';
$cookie_value = get_the_ID();
$init_value = array($cookie_value);
$init_value = serialize($init_value);
//echo $init_value;
setcookie(\'favorites\', $init_value, time() + (86400 * 30), "/");
wp_redirect($_SERVER[\'HTTP_REFERER\']);
} else {
//echo \'set <br>\';
$cookie_value = get_the_ID();
$prev_value = $_COOKIE[\'favorites\'];
$prev_value = stripslashes($prev_value);
$prev_value = unserialize($prev_value);
array_push($prev_value, $cookie_value);
$new_value = serialize($prev_value);
//echo $new_value;
setcookie(\'favorites\', $new_value, time() + (86400 * 30), "/");
wp_redirect($_SERVER[\'HTTP_REFERER\']);
}
}
?>
这工作正常,post\\u id存储在cookie数组中。使用代码
print_r(unserialize($_COOKIE[\'favorites\']));
我能够打印Cookie并获得所有存储的post\\u id的概览。
Problem/Question
目前,我添加了一个新的快捷码,用于显示收藏夹列表。该列表的每个值都将获得一个用于删除/取消设置该cookie的垃圾按钮。现在,我需要使用以下代码:
<?php
$all_favorites= unserialize($_COOKIE[\'favorites\']);
echo \'<table>\';
foreach($all_favorites as $key => $value) {
echo \'<tr>\';
echo \'Post-ID = \' . $value . \' \';
?>
<form method="POST"><button type="submit" class="btn btn-default" name="delete"><span class="glyphicon glyphicon-trash"></span></button>
<input type="hidden" name="delete_id" value="<?php echo $value; ?>" />
</form><br>
<?php
echo \'</tr>\';
}
echo \'</table>\';
if (isset($_POST[\'delete\'])){
//function for setting new cookie, function is displayed on each page before the get_header()
set_cookie_delete();
}
?>
这部分代码的输出:
Edit
功能:
<?php
function set_cookie_delete(){
$all_favorites = unserialize($_COOKIE[\'favorites\']);
$delete_id = $_POST[\'delete_id\'];
echo \'deleted value = \' . \' \' . $delete_id . \'<br>\';
$array_delete = array_diff($all_favorites, array($delete_id));
$array_delete = serialize($array_delete);
print_r($array_delete);
wp_redirect($_SERVER[\'HTTP_REFERER\']);
setcookie(\'favorites\', $array_delete, time() + (86400 * 30), "/");
//echo \'<br><br>\';
//print_r($_COOKIE);
}
?>
我不明白的是
setcookie();
不工作。它位于页面的开头,我首先刷新页面,以便可以设置cookie,对吗?
我们将感谢您的帮助,提前感谢!