Where does wp_redirect need to be placed to make it work?

All we need is an easy explanation of the problem, so here it is.

I’ve got a front end post editing page located at mysite/post_id/edit and am trying to redirect users that are not the author back to the post. Here’s the code I’m working with:

    <?php
    global $current_user; get_currentuserinfo();
    if($post->post_author != $current_user->ID):
    wp_redirect( the_permalink() ); exit;
    ?>

The problem I’ve been having is that this seems to just display the post’s permalink rather than redirecting.

wp_redirect says “wp_redirect will not be called if the page has started, so make sure to call it higher up.” – but after having placed the code at the top of the header.php file I still received the same issue of the permalink being displayed rather than redirecting.

Where would be the appropriate place to add this code to make it redirect?

Thanks in advance!

EDIT: Tried something with milo’s advice, but will follow Tommix’s post before I update on Milo’s

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Once you’re in the template it’s too late, as headers have already been sent. You have to hook earlier in the request to check, like the template redirect hook:

add_action( 'template_redirect', 'wpse52455_redirect' );

function wpse52455_redirect(){
    // do your check and call wp_redirect here
}

Note that this will get called on every request, so you also need to do a check that the current page is your edit page.

EDIT – the above code should go in your theme’s functions.php file.

Method 2

you might need to add some ‘priority’ to the action call.
Like:

add_action('template_redirect', 'user_logged_in', 1, 1);

Method 3

Fully working ANSWER:

global $current_user; get_currentuserinfo();
if($post->post_author != $current_user->ID){
wp_redirect(get_post_permalink($post->ID)); 
 exit();
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply