Add a ‘Back To Search Results’ link to property details pages
A common feature on property sites is add a ‘Back To Search’ link or button on the full details page, allowing users to return to their previous search after clicking into one of their results.
Although we don’t offer this out of the box at the moment, it is possible to achieve by following the below steps.
Step 1: Enable sessions
Once a user runs a search we’ll be storing the full URL, including query string, in a session. As a result, the first thing we need to do is enable PHP sessions on our site. You can do this by adding the following to your theme’s functions.php file:
add_action('init', 'my_start_session', 1); function my_start_session() { if (!session_id()) { session_start(); } } add_action('wp_logout', 'my_end_session'); add_action('wp_login', 'my_end_session'); function my_end_session() { session_destroy(); }
Step 2: Store search query in a session
Now we need to check if we’re on the search page and, if so, add the full URL and query to the session for use later on. Again, add the following to your theme’s functions.php file:
add_action( 'init', 'set_last_search' ); function set_last_search() { if ( !function_exists('ph_get_page_id') ) { // Prevent fatal error, just in case Property Hive isn't active return false; } if ( !isset($_SESSION['last_search']) ) { $_SESSION['last_search'] = ''; } if ( (strpos( "http://" . strtolower($_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']), strtolower(get_permalink(ph_get_page_id( 'search_results' ))) ) !== FALSE) || (strpos( "https://" . strtolower($_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']), strtolower(get_permalink(ph_get_page_id( 'search_results' ))) ) !== FALSE) ) { // if on the property search pages and a query string set $_SESSION['last_search'] = $_SERVER['REQUEST_URI']; if (strpos($_SERVER['REQUEST_URI'], '?') === FALSE) { $_SESSION['last_search'] = $_SERVER['REQUEST_URI'] . '?' . $_SERVER['QUERY_STRING']; } } session_write_close(); }
Step 3: Display 'Back To Search' link on property details page
Now we have the query in a session, all we need to do is update the details page where we want to ‘Back To Search’ link to appear by adding the following:
if ( isset($_SESSION['last_search']) && $_SESSION['last_search'] != '' ) { echo '<a href="' . $_SESSION['last_search'] . '">' . __( 'Back To Search', 'propertyhive' ) . '</a>'; } else { // Cater for when user might've visited URL direct // In which case just link back to search page echo '<a href="' . get_permalink(ph_get_page_id( 'search_results' )) . '">' . __( 'Back To Search', 'propertyhive' ) . '</a>'; }
Note: If you're using Yoast SEO you'll also need to add the following to prevent issues with sessions being overwritten when prefetching:
add_filter( 'wpseo_prev_rel_link', '__return_empty_string' ); add_filter( 'wpseo_next_rel_link', '__return_empty_string' );