How to pass a message using template_redirect

I'm using the following function to redirect a post to another using custom field. It's working just fine until I added the line#8 to pass an ID so that I can grab it in to the post (to where was redirected), and show a custom message that, you are redirected from that particular post:

function project_do_redirect() {
    if( !is_singular( 'mycpt' )  !is_single() )
        return;

    global $post;
    $redirect_post_id = get_post_meta( $post-ID, 'redirect', true );
    $redirect_url = $redirect_post_id ? get_permalink( $redirect_post_id ) : false;
    $redirect_url = esc_url( add_query_arg( 'redir_from', $post-ID, $redirect_url ) );
    if( $redirect_post_id ) {
        wp_redirect( $redirect_url, 301 );
        exit;
    }
}
add_action( 'template_redirect', 'project_do_redirect' );

Problem is:
If I was redirected from post #12 to post #13, the ?redir_from= shows 13 instead of 12. So the thing is not actually working as expected.

So, without passing any parameter to the URL, how can I pass a message to the redirected page?

Topic template-redirect wp-redirect redirect Wordpress

Category Web


You could approach the problem from the other side and look up the post based on the HTTP_REFERER, available in the $_SERVER superglobal:

http://php.net/manual/en/reserved.variables.server.php

You could perform a lookup of the page based on the URL of $_SERVER['HTTP_REFERER'] and get post information that way. You can also keep your 301s cleaner by not adding referrer query vars, and put the 301s in the .htaccess or Apache config as one-liners:

RedirectPermanent /old-path /new-path

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.