我正在试图弄清楚如何显示我的网站内的最后3-5个左右的页面,一个人已经访问过。我做了一些搜索,但我没有找到这样做的可湿性粉剂插件,如果有人知道一个,请告诉我在那个方向:)如果没有,我将不得不从头开始编写它,这就是我需要帮助的地方。
我一直在尝试理解数据库及其工作原理。我假设这就是PHP的神奇之处,除非有使用cookie的javascript选项。
我对所有想法都持开放态度:P &谢谢
发布于 2011-08-19 02:59:58
如果我要编写这样一个插件,我会使用会话cookie通过array_unshift()和array_pop()来填充数组。它会像这样简单:
$server_url = "http://mydomain.com";
$current_url = $server_url.$_SERVER['PHP_SELF'];
$history_max_url = 5; // change to the number of urls in the history array
//Assign _SESSION array to variable, create one if empty ::: Thanks to Sold Out Activist for the explanation!
$history = (array) $_SESSION['history'];
//Add current url as the latest visit
array_unshift($history, $current_url);
//If history array is full, remove oldest entry
if (count($history) > $history_max_url) {
array_pop($history);
}
//update session variable
$_SESSION['history']=$history;现在,我已经对此进行了动态编码。可能存在语法错误或打字错误。如果出现这样的错误,只要发个通知,我就会改正。这个答案的目的主要是为了对概念进行证明。您可以根据自己的喜好对其进行调整。请注意,我假设session_start()已经存在于您的代码中。
希望能有所帮助。
===============
嘿!很抱歉回答得太晚了,我出城几天了!:)
此插件用于回答您使用LI标记的打印输出解决方案的请求
这就是我要做的:
print "<ol>";
foreach($_SESSION['history'] as $line) {
print "<li>".$line.</li>";
}
print "</ol>"; 就这么简单。您应该在这里阅读foreach循环:http://www.php.net/manual/en/control-structures.foreach.php
至于session_start();,请将其放在使用任何$_SESSION变量之前。
希望它能有所帮助!:)
发布于 2020-02-20 21:51:27
我将为WordPress 5+更新和翻译上面的代码,因为原始问题有wordpress标签。请注意,您不需要session_start() anywhere。
接下来,将以下代码添加到您的singular.php模板(或single.php + page.php模板,取决于您的需要):
/**
* Store last visited ID (WordPress ID)
*/
function so7035465_store_last_id() {
global $post;
$postId = $post->ID; // or get the post ID from your template
$historyMaxUrl = 3; // number of URLs in the history array
$history = (array) $_SESSION['history'];
array_unshift($history, $postId);
if (count($history) > $historyMaxUrl) {
array_pop($history);
}
$_SESSION['history'] = $history;
}
// Display latest viewed posts (or pages) wherever you want
echo '<ul>';
foreach ($_SESSION['history'] as $lastViewedId) {
echo '<li>' . get_permalink($lastViewedId) . '</li>';
}
echo '</ul>';您还可以通过在single-cpt.php模板中放置so7035465_store_last_id()函数来存储最近查看的自定义帖子类型(CPT)。
您也可以将其添加到钩子中,或者将其作为操作注入到模板中,但这超出了本问题的范围。
https://stackoverflow.com/questions/7035465
复制相似问题