[워드프레스] wp_redirect() 함수가 작동하지 않는 경우

wp_redirect() 함수는 header가 전송되기 전에 로드되어야 한다고 하네요(wp_redirect()에 대한 자세한 내용은 WordPress Codex 문서를 참고하세요). 그래서:

<?php
/**
* .. Template 주석
*/

get_header();

if(...) {
...
if(...) {
...
wp_redirect($url);
exit();
}
}
?>

위와 같이 header() 다음에 위치시키면 제대로 작동하지 않고 헤더 부분을 wp_redirect() 블록 아래로 이동시켜면 제대로 작동합니다.

<?php
/**
* .. Template 주석
*/
if(...) {
...
if(...) {
...
wp_redirect($url);
exit();
}
}
get_header();
?>
// 참고: http://wordpress.stackexchange.com

그리고 다음과 같은 코드의 경우에도 제대로 작동하지 않습니다.

echo '<script>alert("set thumbnail")';
$location = empty($_POST['redirect_to']) ? get_redirect_link() : $_POST['redirect_to'];
wp_safe_redirect( $location );
echo '<script>alert("End Loop");</script>';

이 경우 echo 부분을 제거하면 제대로 작동합니다(참고).

wp_redirect()는 템플릿 내에서는 header()가 이미 전송되었기 때문에 사용하기에 너무 늦게 되므로, template redirect 액션 등의 후크를 사용하여 더 일찍 체크하도록 해야 합니다.

add_action( 'template_redirect', 'wpse52455_redirect' );

function wpse52455_redirect(){
// 여기에서 체크하여 wp_redirect 호출하기
}
// 참고: stackexchange

"Headers Already Sent" 메시지가 표시될 경우 이 글을 참고해보시기 바랍니다.

참고:


댓글 남기기

* 이메일 주소는 공개되지 않습니다.