0

Is there a Wordpress way of detecting which post or page on the site you linked-from?

The aim is to display custom content, in this case a category archive grid at the bottom of the current page, depending on which page you were last on.

If not a directly Wordpress way, then a best-practices php way of doing this, like an easily-accessible place in the database?

  • 1
    I don't know any wordpress way but you can have a url variable ie mydomain.com/a-page/?ref=5 where 5 is the ID of the post/page of the previous page – Laxmana Jul 21 '14 at 20:40
  • That could work. Something like: $genre_url = add_query_arg('genre', $term->slug, get_permalink()); – simbasounds Jul 21 '14 at 20:50
  • Or $_SESSION or, having just discovered it, the 3rd party $wp_session library: eamann.com/tech/introducing-wp_session – simbasounds Jul 21 '14 at 21:02
  • With sessions you have to save every time the current page where the user is and also handle expired sessions etc. I think with urls it would be easier as this would be for everyone and not specifically to some kind of users. For the links better to add a filter codex.wordpress.org/Plugin_API/Filter_Reference/post_link – Laxmana Jul 21 '14 at 21:20
0

To encode the URLs on the source page, in this case 'home':

function append_query_string( $url, $post, $leavename ) {
    if ( $post->post_type == 'post' ) {
        $url = add_query_arg( 'source', 'home', $url );
    }
    return $url;
}
add_filter( 'post_link', 'append_query_string', 10, 3 );

This adds ?source=home to the end of post link URLs on the home page.


To decode the URL on the target page ie. create a variable with 'home' detected as its value in this example:

$posturl =  $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
parse_str( parse_url( $posturl, PHP_URL_QUERY ), $get_args);
$source = $get_args['source'];


Thanks to Laxmana for the suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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