Created
July 2, 2015 17:55
-
-
Save ccurtin/6491e5132bc57f6cf979 to your computer and use it in GitHub Desktop.
Wordpress: redirect attachment pages to homepage url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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