How To Use A 301 Redirect In Your Functions File

WordPress includes some really handy pluggable functions one of which is

wp_redirect()

This function can easily be written into a custom function with a conditional tag and hook to create a 301 redirect.

Here’s a working example which redirects from a page with the slug ‘shop’ to the blog page:

add_action( 'template_redirect', 'redirect_to_blog_page' );
function redirect_to_blog_page() {
    if ( is_page('shop') && ! is_user_logged_in() ) {
      wp_redirect( 'http://www.example.dev/blog/', 301 ); 
	  exit;
    }
}

You can also use code like this to redirect to the home page.

add_action( 'template_redirect', 'redirect_to_home_page' );
function redirect_to_home_page() {
    if ( is_page('shop') && ! is_user_logged_in() ) {
     wp_redirect( home_url(), 301 );
      exit;
    }
}

You don’t need to use a 301 redirect with this function if you don’t want. You can use the wp_redirect() function for any type of redirect.

More Ways To Create Redirects


Comments

3 responses to “How To Use A 301 Redirect In Your Functions File”

  1. […] If you use a strategic slug structure on your website, you can also use wp_redirect to redirect certain slugs to a new URL. This can be handy if you want to redirect all your posts after changing your default permalink […]

  2. Brad, you post some of the most useful, creative stuff.
    Thanks got sharing!

    1. Brad Dalton Avatar
      Brad Dalton

      Thanks Chad

Leave a Reply

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.