- wp_redirect() │ WP 1.5.1
- Return
- Usage
- Examples
- #1 Use this function for hard-coded URLs only!
- How to Use wp_redirect in WordPress
- How the wp_redirect Function Works
- Nature of the wp_redirect Function
- Step 4: Post a Comment
- Step 5: Redirect to an External Page
- Troubleshooting wp_redirect
- How Misconfigured Redirect Can Cause Performance Issues
- Best Practices
- Summary
- wp_redirect() │ WP 1.5.1
wp_redirect() │ WP 1.5.1
Redirects to another page. Note: wp_redirect() does not exit automatically, and should almost always be followed by a call to exit; :
Exiting can also be selectively manipulated by using wp_redirect() as a conditional in conjunction with the wp_redirect and wp_redirect_status filters:
This is a pluggable function, and it can be replaced by a plugin. It means that this function is defined (works) only after all plugins are loaded (included), but before this moment this function has not defined. Therefore, you cannot call this and all functions depended on this function directly from a plugin code. They need to be called on plugins_loaded hook or later, for example on init hook. Function replacement (override) — in a plugin you can create a function with the same name, then it replace this function.
Hooks from the function
Return
Usage
wp_redirect( $location, $status, $x_redirect_by );
$location(string) (required) The path or URL to redirect to. $status(int) HTTP response status code to use. (Moved Temporarily).
Default: ‘302’ $x_redirect_by(string) The application doing the redirect.
Default: ‘WordPress’
Examples
#1 Use this function for hard-coded URLs only!
wp_redirect() does not validate that the $location is a reference to the current host. This means that this function is vulnerable to open redirects if you pass it a $location supplied by the user. For this reason, it is best practice to always use wp_safe_redirect() instead, since it will use wp_validate_redirect() to ensure that the $location refers to the current host. Only use wp_redirect() when you are specifically trying to redirect to another site, and then you can hard-code the URL.
// We don't know for sure whether this is a URL for this site, // so we use wp_safe_redirect() to avoid an open redirect. wp_safe_redirect( $url ); // We are trying to redirect to another site, using a hard-coded URL. wp_redirect( 'https://example.com/some/page' );
How to Use wp_redirect in WordPress
You can use the wp_redirect function to initiate a redirect at different points on your WordPress site. And in this post, I’ll teach you how to use this function and how it works under the hood.
Before we continue, let me explain how the wp_redirect function works.
How the wp_redirect Function Works
You can find the wp_redirect function in the wp-includes/pluggable.php file with several other helper functions. The job of this function is to redirect your WordPress site to another page. For example, you can use this function to redirect from one page to another based on some condition or your specific need. You may also use it to redirect users to an external website.
Nature of the wp_redirect Function
At the time of this writing, the following code shows how the wp_redirect function is implemented:
Step 4: Post a Comment
In order to test the work you’ve done so far, try to post a new comment.
Go to any post on your blog, type some comments in the text field, and submit. You should be redirected to a /thank-you page within your site. If this page does not exist, you’ll see a standard WordPress 404 error page.
Step 5: Redirect to an External Page
Besides redirecting users to another page on your website, you can also use the wp_redirect function to redirect users to another website. For example, you can redirect all the traffic on your site to another site using a hook that fires the moment a page is requested. You can do a redirect that takes users to google.com just to test how this works.
First, create another function that calls wp_redirect. This is similar to what you did in step 1 above. The following code shows the function:
function redirect_to_google() < wp_redirect('https://google.com'); exit(); >
To finish, create a new action hook for when you want the redirect to occur and attach the above function. Here’s an example using the after_setup_theme action:
add_action( 'after_setup_theme', 'redirect_to_google' );
Once you’re done, try loading any page on your website, and you should be redirected to Google.com.
Troubleshooting wp_redirect
You can run into several issues while using wp_redirect. Some of the challenges you may run into due to the wrong use of wp_redirect include performance issues like your site running slower, or even poor impact on your SEO.
Some of these issues include looping redirects and PHP header errors. Let’s take a look at an example of how a misconfigured wp_redirect may lead to a PHP header error.
How Misconfigured Redirect Can Cause Performance Issues
In PHP, you can redirect user requests using header(‘location: TARGET_URL’) . However, this function requires that your page outputs no data before calling it. In a case when you call the wp_redirect function from a place where WordPress has already outputted some HTML, you may run into an error with the famous “headers already sent …” message. This type of error can cause your redirect to fail completely and can flood your error logs with warning messages for every request sent to the affected URL.
To fix this problem, always attach the wp_redirect function to a hook that’s triggered before any HTML is rendered.
Best Practices
The following are some best practices for using wp_redirect to redirect pages in WordPress:
- Don’t call the wp_redirect function after any code that prints output to the screen. Doing so may lead to PHP header errors.
- WordPress has several hooks for plugin development and customizing your site, and you should use the correct hook to initiate your redirect.
- Always use the right redirect status code as using the wrong code may break your SEO.
- Avoid chaining redirects or redirect loops as this may lead to a poor user experience and impact your SEO.
- Always call the exit() function after calling wp_redirect() .
Summary
In this post, you saw how the wp_redirect function works. It’s a utility function that makes it easy to direct users of your WordPress site from one page to another. The post also provided a tutorial on how to redirect a user to another page after an action like posting a new comment. It’s also possible to redirect users to an external site using the wp_redirect function, and we showed you an example of how to do that. Finally, we listed some best practices and how to troubleshoot redirects.
If you’re interested in web performance and making better experiences for your users, check out Request Metrics client-side observability tools.
This post was written by Pius Aboyi. Pius is a mobile and web developer with over 4 years of experience building for the Android platform. He writes code in Java, Kotlin, and PHP. He loves writing about tech and creating how-to tutorials for developers.
wp_redirect() │ WP 1.5.1
Перенаправляет (редиректит) на указанный УРЛ, можно указать статус редиректа (301, 302. ). Для правильной работы функции нужно указывать полный УРЛ:
http://www.example.com/blog/post_name ftp://ftp.example.com/users/h/harriet/www/
В WordPress есть аналогичная функция для редиректа: wp_safe_redirect(). Отличается тем, что проверяет переданный адрес и сравнивает его со списком разрешенных хостов, если хост не найден, то перенаправления не происходит. «Белым» списком можно управлять с помощью фильтра allowed_redirect_hosts.
ВАЖНО! wp_safe_redirect() рекомендуется использовать всегда, особенно когда $url передается пользователем. Тогда как эту функцию нужно использовать, когда мы намеренно хотим перенаправить пользователя на другой сайт, как правило тут $url жестко прописывается в коде, а не передается пользователем.
// мы точно не знаем указан URL на наш сайт или нет и нам нужно избежать неожиданных редиректов. wp_safe_redirect( $url ); // мы намеренно перенаправляем на другой сайт, URL прописываем жестко. wp_redirect( 'https://example.com/some/page' );
Функция вызовет PHP ошибку (Output already started. Headers not sent.), если использовать функцию после того, как заголовки (header) были отправлены. Т.е. если мы вызовем функцию в файле темы, отвечающем за вывод контента, то функция работать не будет. В таких случаях, в виде некой альтернативы, можно использовать редирект на javascript: document.location.href = ‘http://example.com’;
Это pluggable функция — т.е. её можно заменить из плагина. Это значит, что она будет работать (подключается) только после подключения всех плагинов, а до этого момента функция еще не определена. Поэтому нельзя вызывать эту и зависящие от неё функции прямо из кода плагина. Их нужно вызывать через хук plugins_loaded или позднее, например хук init. Замена функции (переопределение) — в плагине можно создать функцию с таким же названием, тогда она заменит текущую функцию.