I have a "Go back button":

$url = htmlspecialchars( $_SERVER['HTTP_REFERER'] );
echo "<a href='$url'>back</a>";

I need to display the page title of the $url, something like this:

$url = htmlspecialchars( $_SERVER['HTTP_REFERER'] );
echo "<a href='$url'>Go back to the INSERT PAGE TITLE HERE</a>";

Does anyone know how to do this?

  • You have a system will fail in many many instances. HTTP Referers are extremely unreliable as most page request are done anonomously. In these case the http refererer will be empty, breaking your back button ;-) Commented Dec 15, 2015 at 5:20
  • This sounds like a not very well thought of idea. Most people get to your page from google or facebook or any other sharing medium. Doing some extra work just for the people that internally navigate your site doesn't sound like worth the effort. And it is not that simple as you need to handle coming from home page, category page, author page etc, and not only other posts. Commented Dec 15, 2015 at 5:23

1 Answer 1


WordPress has a function called url_to_postid that may work in this situation. You can try the following (untested):

    $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
    $back_id = url_to_postid($_SERVER['HTTP_REFERER']);
    if( $back_id > 0 ){
         $back_title = get_the_title( $back_id );
         echo "<a href='{$url}'>Go back to the {$back_title}</a>"; 
  • Every if should have an else...... ;) In this case the else part is as important as people will come from home page and in shops from the category page Commented Dec 15, 2015 at 5:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.