using wp_redirect to redirect wordpress pages

18,717

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();
  }
}
Share:
18,717
ChrisP777
Author by

ChrisP777

Updated on June 24, 2022

Comments

  • ChrisP777
    ChrisP777 almost 2 years

    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?

  • ChrisP777
    ChrisP777 over 7 years
    if it is possible, could you please tell me what code could go into some_condition() section? I am thinking I should use something like is_page ([link]developer.wordpress.org/reference/functions/is_page/[‌​/link]) will do the work but I am not sure if i can say is_page('example.com/contact-us-3')
  • ChrisP777
    ChrisP777 over 7 years
    Can I also add multiple if statements for couple more pages?
  • timk260
    timk260 over 7 years
    yes. Just check for each condition separately and redirect as desired.