301 redirect WordPress posts from category to a different domain

If you need to redirect all posts from a category to a different domain you can do this very easily from functions.php

There are 2 parts to setup the redirect to a new domain for all the posts in a category:

  • using a hook to intercept the post delivery
  • read the posts slug and redirect them to the new domain.

Using the template_redirect hook to catch the post display before it happens

The template_redirect fires before determining which template to load so it’s what we need.

Let’s build a function and attach it to the hook:

function redirect_page() {

}
add_action( 'template_redirect', 'redirect_page' );

Select all posts in a category

Selecting all posts in a category is very easy with “in_category”:

if ( in_category('category-slug') ) {
}

Read the WordPress post slug and build the redirect to the new domain

For this we need some plain php: $_SERVER[‘REQUEST_URI’]

list($url_path,$params) = explode('?',$_SERVER['REQUEST_URI']);
$path_parts = explode('/',trim($url_path,'/'));

Now we are ready to assemble everything:


function redirect_page() {
	$redirect_to = false;
	list($url_path,$params) = explode('?',$_SERVER['REQUEST_URI']);
	$path_parts = explode('/',trim($url_path,'/'));
	if ( in_category('category-slug') ) {
		wp_redirect ( 'https://www.new-domain.com/'.$path_parts[0], 301 ) ; exit;
	} 
}
add_action( 'template_redirect', 'redirect_page' );