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() )

    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 );
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?

  • I tried this on my local installation and it works as expected: I have a post (5) with a post meta field called redirect with a value of 1. When I visit post 5 on the frontend, I get redirected to post 1 and ?redir_from=5, as expected. I would verify your IDs and custom meta. Can you run the following query: SELECT * FROM wp_postmeta WHERE meta_key = 'redirect' AND post_id IN (12, 13) and provide the output? – phatskat Feb 5 '19 at 5:15

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


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

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.