Search code examples
phpjavascriptjquerywordpressbuddypress

How to show a users last visited pages in wp / buddypress?


im trying to figure out how i can show the last 3-5 or so pages within my site a person has visited. I did some searching, and I couldn't find a WP plugin that does so, if anyone knows of one, please point me in that direction :) if not, I'll have to write it from scratch, and thats where i'll need the help.

I've been trying to understand the DB and how it works. I'm assuming that this is where the magic will happen, with PHP, unless there is a javascript option using cookies to do it.

Im open to all ideas :P & Thank you


Solution

  • If i were to code such a plugin, i'd use the session cookies to populate an array via array_unshift() and array_pop(). it'd be as simple as :

    $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;
    

    Now i've coded this on the fly. There might be syntax errors or typos. If such a mistake appears, just put a notice and i'll modify it. The purpose of this answer is mostly to make a proof of concept. You can adapt this to your liking. Please note that i assume that session_start() is already in your code.

    Hope it helps.

    ===============

    Hey! Sorry about the late answer, i was out of town for a couple of days! :)

    This addon is to answer your request for a print out solution with LI tags

    Here's what i'd do :

    print "<ol>";
    foreach($_SESSION['history'] as $line) {
         print "<li>".$line.</li>";
    }
    print "</ol>"; 
    

    Simple as that. you should read the foreach loop here : http://www.php.net/manual/en/control-structures.foreach.php

    As for the session_start();, put it before you use any $_SESSION variables.

    Hope it helped! :)