Disable Attachment Pages in WordPress

01/30/2024
Back to Gists
<?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
);