Whitelist all sub-sites for wp_safe_redirect in WordPress Multisite

In WordPress, there are two functions for redirecting a page- wp_redirect and wp_safe_redirect.

wp_redirect can be used to redirect to any url.

wp_safe_redirect can only redirect to current site. In case any external url is provided, the page is redirected to wp-admin.

For security, it is recommended to use wp_safe_redirect function for any redirects. This works fine for single WordPress installation. But in case of subdomain based WordPress multisite, this fails because each sub-domain is an individual domain for wp_safe_redirect.

What if we want to use wp_safe_redirect to redirect our pages only within network and not outside?

For this purpose, WordPress has a filter to add additional domains to the wp_safe_redirect whitelist. You can add any domain or sub-domain, internal or external, through this method.

In this article, we will focus on how to whitelist all the sub-domains of a network.

Just add the following code to your custom plugin or child theme’s function.php file.

// Filter to add all subdomains to wp_safe_redirect whitelist
add_filter( 'allowed_redirect_hosts', 'whitelist_all_subdomains' );

function whitelist_all_subdomains( $hosts ) {
    $sites = get_sites();
    $domains = array();

    foreach ( $sites as $site ) {
        $domains[] = $site->domain;
    }

    return array_merge( $hosts, $domains );
}

This code gets all the sites through get_sites function and iterates all the sites to create an array of all domains/sub-domains of sub-sites. It then adds that to the whitelist.

If you try now, you will see that page redirects across sub-sites of a network using "wp_safe_redirect" are flawless.

Share this:

Leave a Comment

Your email address will not be published. Required fields are marked *