I am am working on a listing type theme and have a search results page that take people to a more details page. I also have links throughout the site that will also take visitors straight to the more details page.

On the more details page I would like to display a 'Back to search results' link but only if the user came from the search results page.

The only way I can think to do this is to get the page template of the previous page search-results.php and use that as the criteria for displaying the link.

Is there a way to get the page template of the previous page, or any other way to achieve this?

  • This is not a WordPress issue: stackoverflow.com/questions/165975/determining-referer-in-php
    – s_ha_dum
    Commented Dec 26, 2015 at 15:20
  • @s_ha_dum But that does not get me the page template name which I believe is specific to WordPress.
    – Naz
    Commented Dec 26, 2015 at 15:27
  • The idea that you need the page template is incorrect. You need an identifier for the search page which you would pass via the URL (of check the $_REQUEST referrer.
    – s_ha_dum
    Commented Dec 26, 2015 at 15:30
  • That works but is not the best way to do it.
    – Naz
    Commented Dec 26, 2015 at 15:48
  • Actually, passing an identifier is the most reliable way to do it, but suit yourself.
    – s_ha_dum
    Commented Dec 26, 2015 at 15:56

1 Answer 1


You can use wp_get_referer(); to get a URL of previous page from where user came. Then get the last slug part of the URL. Then compare if the slug matches with slug of your custom search-result page template. Then you can decide whether to show or not to show 'Back to search results' link. Please try below code and feel free to update as intended:


    $ref_url = wp_get_referer();

    $results = explode('/', trim($ref_url,'/'));

    if(count($results) > 0){
        //get the last record
        $last_word = $results[count($results) - 1];

    if ( $last_word == "about" )
        echo "<a href='$ref_url'>Back to search results</a>";

  • This will break with some permalink structures.
    – s_ha_dum
    Commented Dec 26, 2015 at 15:55
  • Yes. I have assumed pretty permalinks are active. Commented Dec 26, 2015 at 16:57
  • It is possible (not from the backend without a plugin) to change page permalink structure too so it isn't just a matter of having pretty permalinks enabled or disabled. It is a condition that should be noted.
    – s_ha_dum
    Commented Dec 26, 2015 at 17:11
  • I have used a part of the search string to test if the visitor came from a search page, is that what you meant by identifier?
    – Naz
    Commented Dec 27, 2015 at 14:47

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.