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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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 😉
Method 2
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; ?>" rel="nofollow noreferrer noopener" class="previous-history-link">The last page from history</a>
<?php endif; ?>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0