Code Stuff


Yes, web browsers have a back button, but sometimes it is useful to have one on your site itself. On one of my sites we have a section where readers might need to go back and forth from a page full of links. So after a reader clicks one of these links we've placed our own back button on the following pages in about the same location where the mouse stopped when they clicked. No long mouse movements from the the mid-right part of the screen all the way up to the top-left corner of the screen needed just to go back!

Seems like a simple thing. But we had a few things we wanted to do to make it even better. First of all, we only wanted the back button to appear on posts in the specific category that had this quick back-and-forth linkage. Second, if another website linked to one of these pages we didn't want the back button to take them off our site when clicked. And third, if someone were to click a link to one of these pages from somewhere else on our site (such as the archives or the search results) we wanted the back button to correctly take them back there and not our links page.


<?php if ( in_category('5')) { $referer = $_SERVER['HTTP_REFERER'];
	$is_us = @strpos( $referer, 'OurDomainName'); if($is_us)
	{ echo '<a href="' . $referer . '"><img src="arrow-back.png"></A>'; }
	else { echo '<a href=""><img src="arrow-back.png"></A>'; } } ?>

Line 1 checks that we are only running this code if we are in a specific category. If so the variable "$referer" equals the referring URL.

Line 2 searches the referring URL for OurDomainName (change this to your domain name obviously). Hopefully, your domain name will not be in the URL of someone else's site!

If your domain name is in the referring URL we will assume the reader is coming from your site and line 3 will print the back button image to the screen.

If your domain name is not in the referring URL we will assume the reader has come to this page from another website. To prevent our back button from linking to them, line 4 prints the back button but links it to your home page.

If you wanted this back button to appear in all categories, remove everything starting with the word "if" in line 1 all the way to and including the opening curly bracket in line 1. Then remove one of the closing curly brackets near the end of line 4.

If you'd prefer you could make the back button just not appear if the referrer is another website, rather than make the it link to you. To do this just remove everything in the code starting with the word "else" in line 4 all the way to and including the first closing curly bracket.