While coding a Wordpress site, I wanted to add a back button for posts and pages.
Hierarchical pages should obviously point back to their parents, but what of non hierarchical pages?
If a user navigated from the "Gallery" page to the "About" page - I would like the sites "back" button to return him to the "Gallery" page. This could be easily implemented using JavaScript but why use user-side scripting when you can generate the code on the server side?
The obvious solution would be to use the referring URL as a target for our "back" button. We must now avoid two special cases:
Hierarchical pages should obviously point back to their parents, but what of non hierarchical pages?
If a user navigated from the "Gallery" page to the "About" page - I would like the sites "back" button to return him to the "Gallery" page. This could be easily implemented using JavaScript but why use user-side scripting when you can generate the code on the server side?
The obvious solution would be to use the referring URL as a target for our "back" button. We must now avoid two special cases:
- The page is a sub-page and the back button should point to its parent.
- The previous URL was an off-site URL, and the back button should not appear at all.
$ref_url = wp_get_referer(); $ref_parse = parse_url($ref_url); $my_parse = parse_url(get_permalink()); if (($ref_url==get_permalink() || empty($ref_url)) && $post->post_parent) { $show_back_to_parent=true; $ref_url = get_permalink($post->post_parent); } if ($ref_parse[host]==$my_parse[host] || $show_back_to_parent) { echo $ref_url; }