wp_safe_redirect

Home » Functions » wp_safe_redirect

Function Name: wp_safe_redirect

Explanation: The wp_safe_redirect function is a powerful tool in WordPress that allows developers to redirect users to other pages within their website or to external URLs in a safe and secure manner. It ensures that the redirect is valid and prevents potential security risks or malicious actions.

When using wp_safe_redirect, it is important to note that it should be used within the WordPress template files or plugin/theme files rather than within the functions.php file. This is because the function relies on WordPress being fully loaded in order to work properly.

Usage: To redirect a user to a specific page within the WordPress website, you can use the wp_safe_redirect function as follows:

<?php
wp_safe_redirect( home_url( '/new-page' ) );
exit;
?>

In this example, the user will be redirected to the "new-page" URL within the current WordPress website. The home_url() function is used to generate the absolute URL for the desired page. The exit statement is necessary to ensure that any further code execution is stopped after the redirection.

It is important to always use wp_safe_redirect instead of the regular header("Location: ...") function as it provides an additional layer of security by validating and sanitizing the URL being redirected to. This helps prevent open redirect vulnerabilities and protects your website and users from potential threats.

Remember, using wp_safe_redirect is crucial when handling redirects in WordPress to ensure a safe and reliable experience for your website visitors.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.