简体   繁体   中英

wp_redirect causes "Cannot modify header information"

I am trying to restrict users who are not logged in from accessing certain pages on the website by adding:

if (!is_user_logged_in()) {
    wp_redirect(esc_url(site_url('/')));
    exit();
}

But it generates the error

Cannot modify header information.

See screenshot of错误信息

Where did you put your code?

Try adding this to your functions.php file.

add_action('init', 'check_for_user_logged_in');

function check_for_user_logged_in()
{
    if (!is_user_logged_in()) {
        $currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $redirectUrl = site_url('/');

        if ($currentUrl != $redirectUrl) {
            wp_redirect($redirectUrl);
            die();
        }
    }
}

Just try by adding ob_start before redirect as below

if (!is_user_logged_in()) {
    ob_start();
    wp_redirect(esc_url(site_url('/')));
    exit();
}

Or redirect using javascript as below

<?php if (!is_user_logged_in()): ?>
    <script>
        window.location.href='your url';
    </script>
<?php endif; ?>

The redirection should be the first thing you send to the user. Here, you called get_headers() before, which sent the headers to the user and thus you cannot use a redirection afterwards.

Try calling the wp_redirect at the beginning of your file.

<?php
if (!is_user_logged_in()) {
    wp_redirect(esc_url(site_url('/')));
    exit();
}

// ... Rest of your php file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM