Validating redirect URLs in WordPress with wp_validate_redirect

The WordPress wp_validate_redirect function is used to validate and sanitize a URL for redirection. It checks if the URL is safe and allowed for redirection within the WordPress environment.

This function can be useful for ensuring that any user-provided or dynamic URLs used for redirection are properly validated and sanitized to prevent potential security vulnerabilities such as open redirects or malicious redirection.

  • It helps to protect against unauthorized or unsafe redirections.
  • It ensures that the URL is properly formatted and safe for redirection within the WordPress environment.

Parameters Accepted by wp_validate_redirect Function

The wp_validate_redirect function accepts the following parameters:

  • $location (string, required): The redirect to validate.
  • $fallback_url (string, optional, default value: ”): The value to return if $location is not allowed.

Value Returned by wp_validate_redirect Function

The wp_validate_redirect function returns a string, which is the sanitized URL for redirection.


Example 1: How to validate a redirect URL

$redirect_url = '';
$validated_url = wp_validate_redirect( $redirect_url, home_url() );

The code snippet validates the $redirect_url using the wp_validate_redirect function and stores the validated URL in the $validated_url variable.

Example 2: Redirecting to an External URL

$location = '';
$default = home_url();
$safe_redirect = wp_validate_redirect($location, $default);

In this example, wp_validate_redirect() is used to validate an external URL. If the external URL is not safe, the function will return the home URL of the WordPress site as a fallback, ensuring the redirection stays within a trusted domain.

Example 3: Using with wp_redirect()

$location = '/untrusted/path';
$default = get_bloginfo('url');
$safe_location = wp_validate_redirect($location, $default);
if ($safe_location) {

This example combines wp_validate_redirect() with wp_redirect() to safely redirect users. It first validates the URL, and if it’s considered safe, it proceeds with the redirection using wp_redirect(). This is a common pattern for safely handling redirects to prevent open redirect vulnerabilities.


In conclusion, the wp_validate_redirect function is a crucial tool for ensuring the security and integrity of WordPress websites. By validating and sanitizing user input for redirects, this function helps to prevent malicious attacks such as open redirects and phishing attempts. It is important for developers to utilize this function in their code to protect their websites and their users from potential security vulnerabilities. With its robust validation capabilities, wp_validate_redirect is an essential component of a strong security strategy for any WordPress site.

Related WordPress Functions