Skip to content

Instantly share code, notes, and snippets.

@knolaust
Last active January 30, 2024 14:47
Show Gist options
  • Save knolaust/ce9aad7d642c504e69a334d57e872ebd to your computer and use it in GitHub Desktop.
Save knolaust/ce9aad7d642c504e69a334d57e872ebd to your computer and use it in GitHub Desktop.
Disable Attachment Pages in WordPress
<?php
/**
* Redirect attachments to their parent posts or homepage.
*
* This function checks if the current page is an attachment and if it has a parent post.
* If the attachment has a parent post that is not trashed, it redirects to the parent post.
* If the attachment has no parent or the parent post is trashed, it redirects to the homepage.
*
* Gist Keywords: wordpress, disable attachment, pages
*
* @author Knol Aust
* @version 1.0.0
*/
add_action(
'template_redirect',
function () {
global $post;
if ( ! is_attachment() || ! isset( $post->post_parent ) || ! is_numeric( $post->post_parent ) ) {
return;
}
// Does the attachment have a parent post?
// If the post is trashed, fallback to redirect to the homepage.
if ( 0 !== $post->post_parent && 'trash' !== get_post_status( $post->post_parent ) ) {
// Redirect to the attachment parent.
wp_safe_redirect( get_permalink( $post->post_parent ), 301 );
} else {
// For attachment without a parent redirect to homepage.
wp_safe_redirect( get_bloginfo( 'wpurl' ), 302 );
}
exit;
},
1
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment