[wordpress] How to EASILY 301 redirect all 404 error pages to root domain using WordPress

[复制链接]
查看: 270   回复: 0
发表于 2012-5-22 00:25:57 | 显示全部楼层 |阅读模式
Alright so a few days ago I successfully purchased an expiring domain from an auction site, and after wasting a few hours doing 301 redirects manually (monitoring 404s and adding redirects by hand in .htaccess file) I accidently found this super easy method to 301 redirect all 404 error pages to root domain.

This trick was simply done by a WP core function called wp_redirect(). Here are the parameters for the function:
  1. $location
  2. (string) (required) The absolute URI which the user will be redirected to.
  3. Default: None

  4. $status
  5. (integer) (optional) The status code to use.
  6. Default: 302
复制代码
Here's how the function should be used:
  1. <?php
  2. wp_redirect( $location, $status );
  3. exit;
  4. ?>
复制代码
Here's a real life example
  1. <?php wp_redirect( get_option( 'siteurl' ); exit; ?>
  2. What this does is, calling the get_option('siteurl') will basically return the default domain name that you're using (One that you've set in the Settings > General tab). And then, redirects it using a 302 since we haven't exclusively specified that we need a 301 redirect (302 is the default).
复制代码
But.. this isn't what we want, we need it to redirect with a 301, right?
  1. <?php wp_redirect(get_option('siteurl'),301); ?>
  2. Yep, right there. This basically gets the default domain name and makes the redirect with a 301.
复制代码
So how to redirect all error pages to default domain name (root domain) with a 301?

Simple, create a file and name it 404.php and paste the above code in it, then replace your existing 404.php with it.

Remember that you need to replace the 404.php in your theme folder, which is located at wp-content > themes > your theme.

Enjoy~
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则