using wp_redirect to redirect wordpress pages

2019-05-01 11:07发布

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?

1条回答
别忘想泡老子
2楼-- · 2019-05-01 12:02

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();
  }
}
查看更多
登录 后发表回答