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?
5
) with a post meta field calledredirect
with a value of1
. When I visit post5
on the frontend, I get redirected to post1
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?