I already consulted this post and this post but did not see a solution.

I need to redirect a page based on its $post->post_type and from what little I know, I can get this information inside the template_redirect hook.

So I have code below inside functions.php (of astra-child theme):

add_action('template_redirect', 'redir_sorteio'); 

function redir_sorteio() {
    global $post;
    if ($post->post_type == 'sorteio') 
        wp_redirect('/edicao/?id=' . $post->ID);

And it works perfectly.

But for some reason, errors have appeared within the log, like:

[18-May-2018 01:11:22 UTC] PHP Warning:  Cannot modify header information - headers already sent by (output started at /home/rogeriod/public_html/wordpress/sortemania/wp-content/themes/astra-child/functions.php:32) in /home/rogeriod/public_html/wordpress/sortemania/wp-includes/functions.php on line 1311

Where line 32 of functions.php (above) is the wp_redirect('/edicao/?id=' . $post->ID) and line 1311 of wordpress functions.php is the header command inside do_robotsfunction:

function do_robots() {
    header( 'Content-Type: text/plain; charset=utf-8' );

How can I find out what causes this and resolve it, since wp_redirect is working and no error appears directly to the user?


2 Answers 2


Try replacing wp_redirect with wp_safe_redirect and if you have php closing tag "?>" at end of files, remove them, at least you can check the header.php for php closing tag.

  • I'll try and wait to see if I get no more errors, and then accept you answer. Thanks. May 18, 2018 at 20:41

Actually the answers to change to wp_safe_redirect and put exit(); at the end, partially resolved the problem and it is a solution that only works inside the template_redirect, because in other places the problem persists.

This became a nightmare and I realized that it is also the nightmare of many, until I was able to find in a post an efficient, albeit unorthodox, solution: javascript.

So, after several attempts and errors, I got a stable code like this:

add_action('template_redirect', 'redireciona_sorteio'); 

function redireciona_sorteio() {
    global $post;
    if (isset($post->post_type)) {
        if ($post->post_type == 'sorteio') {
            if (!$post->ID) {
                echo '<script> location.replace("/"); </script>';
            else {
                wp_safe_redirect('/edicao/?id=' . $post->ID);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.