Get previously visited page ID

I would like to get the ID (or permalink) of the page the visitor visited just before visiting the current page - in other words the ID of the last page in the browser history.

Can this be done? Any idea how to do it?

Topic id previous Wordpress

Category Web


I've done this trick like this to allow me to also check if it is one of my pages :

//Get the last page link from history

$prev_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;

//Check if not null and if it contains my blog url

if( !empty( $prev_url ) || strpos( $prev_url, (string)get_blog_details()->domain ) !== false ) :
    //Then display it only if it's one of my blog page ?>
    <a href="<?php echo $prev_url; ?>" class="previous-history-link">The last page from history</a>
<?php endif; ?>

Break this down into two parts:

First, we create a variable that stores that last-visited page URL, like this:

$prev_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

Then, you could either use substr and strpos to trim down everything between ?= and the / after the ID number. like this:

$prev_url = 'http://www.yoursite.com/?p=123';
$id_block = substr($prev_url, strpos($prev_url, "?p=")+1);
$id = substr($id_block, 0, strpos($id_block, "/"));

.. Or, you could use jQuery/Javascript to achieve the same.

I haven't tested this but it should work - let me know how it does! Good luck ;)

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.