You want to redirect a WordPress post to an external URL. Maybe it's an affiliate link, a resource that moved, or a curated link collection.
The naive approach using wp_redirect() with any URL opens security holes. Here's how to do it safely.
The Problem with wp_redirect()
// DON'T DO THIS wp_redirect ( $_GET [ 'url' ] ); exit ;
Enter fullscreen mode
Exit fullscreen mode
This is an open redirect vulnerability. Attackers can craft URLs like:
yoursite.com/post?url=https://malicious-site.com
Enter fullscreen mode
Exit fullscreen mode
And use your domain's reputation to phish users.
Safe External Redirects
WordPress provides wp_safe_redirect() , but it only allows redirects to whitelisted hosts. For external URLs, we need validation:
/** * Safely redirect to an external URL * * @param string $url Destination URL * @param int $status_code HTTP status code (301, 302, 307) */ function safe_external_redirect ( $url , $status_code = 301 ) { // Validate URL format if ( !…