WordPress

How to Implement Redirects to Other Posts or URLs in WordPress

The method for redirecting in PHP and the method for redirecting posts or pages to other URLs in WordPress are slightly different. This article introduces the method for URL redirects in WordPress and precautions when doing this. To redirect in PHP, header('Location ' . $url, true, ($permanent === true) ? 301...

Shou Arisaka
2 min read
Nov 4, 2025

The method for redirecting in PHP and the method for redirecting posts or pages to other URLs in WordPress are slightly different. This article introduces the method for URL redirects in WordPress and precautions when doing this.

To redirect in PHP,


// redirect to top page by some reason
function Redirect($url, $permanent = false)
{
    if (headers_sent() === false)
    {
        header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
    }

    exit();
}

Redirect('https://example.xyz/', 301);

This should work.

Reference: How to make a redirect in PHP? - Stack Overflow

However, in WordPress, If you do it like this:

if ( get_the_ID() == 107 ){

    Redirect('https://example.xyz/', 301);

}

This is impossible. You cannot identify a specific post with get_the_ID and then do a PHP redirect.

As a WordPress specification, header.php is loaded after the header is loaded. It’s essentially static PHP. On the other hand, functions.php operates before the header is loaded, it’s dynamic PHP that can intervene in the system and database.

get_the_ID can only be used in static PHP. This is because get_the_ID is not yet available at the functions.php stage. And Redirect() contains header(). The header() function can only be used in dynamic PHP.

In other words, get_the_ID and header() cannot be used together. If get_the_ID were loaded first, there would still be room, but since header() that does redirects operates first, it’s impossible.

This kind of thing happens occasionally when working with WordPress. It’s good to remember.

Back to the topic, so what do you do?

In header.php,

Either do it in HTML,

if ( get_the_ID() == 107 ){
    echo '   <meta http-equiv="refresh" content="0; URL=https://example.xyz/">  ' ;

}

Or do it in Javascript.

if ( get_the_ID() == 107 ){
    echo '<script type="text/javascript">
    window.location.href = "https://example.xyz/"
</script>' ; 
}

Javascript redirects are fast but can be captured with curl. It’s better to think of redirects not done from the server as merely apparent redirects.

Share this article

Shou Arisaka Nov 4, 2025

🔗 Copy Links