Redirecting Wordpress pages

Another wordpress tip

August 05, 2022 Code

When a user adds a new category, assets, taxonomy, etc to their website, it creates a dedicated template page for those lists. However, this sometimes might cause an issue (especially related with SEO) as it generates weird, broken pages that is meaningless by themselves.

One solution to fix this issue is to write a redirect code which can redirect a user to a different, and relevant page.

This can be done by adding a code in either funtions.php or any individual templates that are used for such lists, which you want to redirect.

For example underneath, is a code for redirecting any category or tag pages and redirecting them to home (root) page.

if ( is_category() || is_tag() ) {
    wp_redirect(get_option('home'), 301);
    exit;
}

It is important to understand that you should add 301 as a second argument so that the code returns a 301 which means permanent deletion. This helps Google understand the link is deleted.

For redirecting any taxonomies, or assets or authors, you can use:

if ( is_author() || is_tax('sample_taxonomy') ) {
    wp_redirect(get_option('home'), 301);
} elseif ( is_attachment() ) {
    global $post;
	  if ( $post && $post->post_parent ) {
		  wp_redirect( esc_url( get_permalink( $post->post_parent ) ), 301 );
		  exit;
	  } else {
		  wp_redirect( esc_url( home_url( '/' ) ), 301 );
		  exit;
	  }
}

If you care considering redirecting any post_type pages:

if ( (is_single() && 'sample_post_type' == (get_query_var('post_type')))) {
    wp_redirect(get_option('home'), 301);
    exit;
}

Bonus: you can also retrieve current root links with:

'https://'.$SERVER['HTTP_HOST']

Invely's