Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using wp_redirect to redirect wordpress pages

Since I don't want to use another plugin to do simple redirect tasks, I decided to use the following code.

wp_redirect( "http://www.example.com/contact-us", 301 );

so here is my question.

Let's say I have a page called "https://www.example.com/contact-us-3/" that needs to redirect to "https://www.example.com/contact-us/".

Or I should say I really want the redirect to happen regardless of http or https, www or non-www. I am want "/contact-us-3/" to redirect to "/contact-us/" page.

Does that mean I have to put the following code inside the wordpress contents? Where do I exactly put the code? function.php in the child theme? I do I specify the page that needs to be redirected? or I do have to create a page "/contact-us-3/" and put the code in the page?

Also, do I have to put the fully qualified domain name url?

like image 676
ChrisP777 Avatar asked Dec 21 '16 17:12

ChrisP777


1 Answers

You may want to put your redirect code into a callback function that is tied to the template_redirect hook. Put code similar to the following in the functions.php file of your theme. The function named "some_condition" (which you write) will determine if the page should be redirected or not.

add_action( 'template_redirect', 'my_callback' );
function my_callback() {
  if ( some_condition() ) {
    wp_redirect( "http://www.example.com/contact-us", 301 );
    exit();
  }
}
like image 157
timk260 Avatar answered Oct 05 '22 22:10

timk260