0

我试图弄清楚如何在我的网站中显示一个人访问过的最后 3-5 个页面。我做了一些搜索,但我找不到这样做的 WP 插件,如果有人知道,请指出我的方向 :) 如果没有,我将不得不从头开始编写它,这就是我的位置我需要帮助。

我一直在尝试了解数据库及其工作原理。我假设这就是使用 PHP 发生魔法的地方,除非有一个使用 cookie 的 javascript 选项来做到这一点。

我对所有想法持开放态度:P & 谢谢

4

2 回答 2

3

如果我要编写这样的插件,我会使用会话 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 变量之前。

希望它有所帮助!:)

于 2011-08-18T18:59:57.883 回答
0

我将为 WordPress 5+ 更新和翻译上面的代码,因为原始问题有wordpress标签。请注意,您不需要session_start()任何地方。

在这里,将下面的代码添加到您的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>';

您还可以通过将so7035465_store_last_id()函数放置在single-cpt.php模板中来存储最新查看的自定义帖子类型 (CPT)。

您还可以将其添加到挂钩或将其作为操作注入模板中,但这超出了此问题的范围。

于 2020-02-20T13:51:26.673 回答