Snippets Library

Disable Attachment Pages

Posted by Editorial Staff

To disable attachment pages in WordPress using a custom function, you can add the following code to your theme’s functions.php file. This code modifies the attachment post type to redirect to the parent post instead of displaying attachment pages. Make sure to back up your theme or use a child theme before making any changes to your functions.php file.

function disable_attachment_pages_redirect() {
global $post;
if (is_attachment()) {
$parent_post = get_post($post->post_parent);
if ($parent_post) {
wp_redirect(get_permalink($parent_post));
exit();
} else {
wp_redirect(home_url());
exit();
}
}
}
add_action('template_redirect', 'disable_attachment_pages_redirect');

Here’s what the code does:

  1. The disable_attachment_pages_redirect function checks if the current page is an attachment page using is_attachment().
  2. If it’s an attachment page, it retrieves the parent post object using get_post($post->post_parent).
  3. If there is a parent post, it redirects to the parent post’s URL using wp_redirect().
  4. If there is no parent post (or an issue with fetching it), it redirects to the home page of your site.

This code will effectively disable attachment pages by redirecting them to their parent posts or the home page.

After adding this code to your theme’s functions.php file, you should no longer see attachment pages, and the attachments will automatically redirect to their parent posts or the home page.

Leave a Reply

Your email address will not be published. Required fields are marked *