You have many plugin which can do redirection for you and are great at doing your job. but sometime you many need to redirect user after some specific event or task. like if user click on some button, it should go to some specific page in your WordPress website or outside to some website. at this point plugins are not helping you to do this. you can only use plugin for the purpose of redirecting of some post/page to some other page/post.
So you need to know about wp_redirect() function.
wp_redirect() is a Pluggable Function
you can find wp_redirect() in wp-includes/pluggable.php
.
so if you are coding a plugin or theme you may need this function to redirect purpose.
i also use this when i was working on a form and i was using WordPress short code to display form and then i apply some conditions to form, if user select what and he will go to some page and like this.
code bellow:
add_action('init', 'get_rate'); function get_rate(){ if(isset($_POST['get_rate'])) { $loan_purpose=$_POST['loan_purpose']; if($loan_ammount<10000) { wp_redirect(home_url('/decline')); } else { wp_redirect(home_url('/approve')); }
so this should work accordingly to conditions. here you see get_rate, its actually that submit button name. i am using function to take data from FORM. i have place this code to functions.php file of WordPress.
then i was in need to redirect user to outside of my WordPress website. i get that working by following code.
wp_redirect("http://www.google.com",301); exit();
at this stage i miss http:// in the start of www.google.com, so page was not redirecting properly and showing address at the end of page url. so you also need to be careful about this. place http:// before the address of some page which you want to redirect.
here is one thing you can also use PHP headers to redirect page but mostly chance is you will get ‘header already sent’ error on your page.
if you will see wp redirect refrence:
wp_redirect()
does not exit automatically and should almost always be followed by exit
.
<?php wp_redirect( $location, $status ); exit; ?>
use this like to 301 redirect
<?php wp_redirect( 'http://www.example.com', 301 ); exit; ?>