Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccurtin/6491e5132bc57f6cf979 to your computer and use it in GitHub Desktop.
Save ccurtin/6491e5132bc57f6cf979 to your computer and use it in GitHub Desktop.
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
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment