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

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

3 s
3

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.

Leave a Comment