ccurtin
7/2/2015 - 5:55 PM

Wordpress: redirect attachment pages to homepage url

Wordpress: redirect attachment pages to homepage url

<?php
/*
* Redirect Attachment Pages
*/
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
	}
}
?>