Using WordPress ‘redirect_this_site()’ PHP function

The redirect_this_site() WordPress PHP function ensures that the current site’s domain is listed in the allowed redirect host list.

Usage

$allowed_redirect_hosts = redirect_this_site();

Parameters

  • $deprecated (array|string, Optional) – Not used. Default: ”

More information

See WordPress Developer Resources: redirect_this_site

Examples

Adding the current site to the allowed redirect hosts

Add the current site’s domain to the allowed redirect hosts list and filter it before using it in a custom redirect function.

// Get the allowed redirect hosts
$allowed_redirect_hosts = redirect_this_site();

// Use the allowed redirect hosts in a custom redirect function
function custom_redirect($location) {
  global $allowed_redirect_hosts;
  if (in_array(parse_url($location, PHP_URL_HOST), $allowed_redirect_hosts)) {
    wp_redirect($location);
    exit;
  }
}

Allowing specific additional domains for redirect

Add custom domains to the allowed redirect host list using the ‘allowed_redirect_hosts’ filter.

add_filter('allowed_redirect_hosts', 'my_custom_allowed_redirect_hosts', 10, 1);

function my_custom_allowed_redirect_hosts($allowed_hosts) {
  $allowed_hosts[] = 'example.com';
  $allowed_hosts[] = 'example2.com';
  return $allowed_hosts;
}

Checking if a redirect URL is valid before redirecting

Use the wp_validate_redirect() function to check if the redirect URL is valid before redirecting.

$redirect_url = 'https://example.com/some-page/';
$valid_redirect_url = wp_validate_redirect($redirect_url, false);

if ($valid_redirect_url) {
  wp_redirect($valid_redirect_url);
  exit;
}

Allowing subdomains of the current site for redirect

Add all subdomains of the current site to the allowed redirect host list.

add_filter('allowed_redirect_hosts', 'my_custom_allowed_subdomains', 10, 1);

function my_custom_allowed_subdomains($allowed_hosts) {
  $site_domain = parse_url(get_site_url(), PHP_URL_HOST);
  $subdomains = array('sub1', 'sub2', 'sub3');

  foreach ($subdomains as $subdomain) {
    $allowed_hosts[] = $subdomain . '.' . $site_domain;
  }

  return $allowed_hosts;
}

Redirecting to a custom URL if the redirect URL is not in the allowed hosts list

Redirect to a custom URL if the given redirect URL is not part of the allowed redirect host list.

$redirect_url = 'https://example.com/some-page/';
$valid_redirect_url = wp_validate_redirect($redirect_url, false);

if ($valid_redirect_url) {
  wp_redirect($valid_redirect_url);
} else {
  wp_redirect(home_url());
}

exit;