skip to Main Content

Image attachment pages show up in search results on website. I need to know how i can remove ones that are currently there. If i can only do this in my database, how can i make sure i delete the actual attachment pages and not the original pages themselves.

here is where the problem is

2

Answers


  1. You can use this small snippet – add it to the functions.php of your child theme :

    function remove_attachments_from_search() {
        global $wp_post_types;
        $wp_post_types['attachment']->exclude_from_search = true;
    }
    add_action('init', 'remove_attachments_from_search');
    

    This will exclude attachment post type from search results.

    Hope this helps

    Login or Signup to reply.
  2. You can disable the media attachment page on Yoast SEO if you have installed it. Or you can paste this to your functions.php

    function myprefix_redirect_attachment_page() {
    if ( is_attachment() ) {
        global $post;
        if ( $post && $post->post_parent ) {
            wp_redirect( esc_url( get_permalink( $post->post_parent ) ), 301 );
            exit;
        } else {
            wp_redirect( esc_url( home_url( '/' ) ), 301 );
            exit;
        }
      }
    }
    add_action( 'template_redirect', 'myprefix_redirect_attachment_page' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search