toggle menu

How to redirect worpress image URL to attachment pages

Manish Singh |01 Apr at 06:04

Hey guys!

I have had problem with worpress image attachment URL which is creating problem for tech SEO, I found the solution for it how to redirect image URL to attachment page with 301 redirection.

You need to put below following code in FUNCTION.PHP inside you theme file

add_action( 'template_redirect', 'wpse27119_template_redirect' );
function wpse27119_template_redirect()
{
// Get out of here if not headed to an attachment page	
if( ! is_attachment() ) return;	

// Find the $post variable representing the page where we're heading
global $post;
if( empty( $post ) ) $post = get_queried_object();	

// Check if post has a parent	
if ($post->post_parent)
	{
	// Yes so find permalink of parent post
	$link = get_permalink( $post->post_parent );
	// Redirect attachment to the parent post
	wp_redirect( $link, '301' );
	exit(); // always call exit after wp_redirect
	}
else	
	{
	// No parent so just redirect to home page
	wp_redirect( home_url(), '301' );
	exit(); // always call exit after wp_redirect
	}
}

 

  • 2 likes
  • 0 comment

Posted:

01 Apr at 06:04

Viewed:

1023 times

Active:

01 Apr at 09:04