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?
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'] : '';
$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, "/"));
I haven't tested this but it should work - let me know how it does! Good luck ;)
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; ?>