Disable images pages on WordPress in just 5 minutes

Marc Wag­ner

April 28, 2021

1 min read|

You want to pre­vent that sin­gle images can be cal­led as indi­vi­du­al page in your Word­Press web­site? Then this litt­le artic­le is just right for you.

You can crea­te a search engi­ne fri­end­ly 301 redi­rect wit­hout any plug­in and with only a few lines of code.

The fol­lo­wing code ensu­res that attach­ments are redi­rec­ted. First, it checks whe­ther the attach­ment was uploa­ded for a page.

If the respec­ti­ve page could be iden­ti­fied, a for­war­ding to this page takes place. Other­wi­se, a redi­rec­tion to the start page is per­for­med.

You can con­ve­ni­ent­ly add the fol­lo­wing code to your theme’s Functions.php (ide­al­ly in the child the­me).

/**
 Disable attachment page
 @see https://themeisle.com/blog/redirect-wordpress-attachment-pages/
 */
 function addRediretToAttachmentPage() {
 if ( is_attachment() ) {
     global $post;
 $url = esc_url( home_url( '/' )); if ( $post && $post->post_parent ) {     $url = esc_url( get_permalink( $post->post_parent )); } wp_redirect( $url , 301 ); exit;
 }
 }
 add_action( 'template_redirect', 'addRediretToAttachmentPage' ); 

By spe­ci­fy­ing the sta­tus code “301”, it is ensu­red that search engi­nes also per­ma­nent­ly update the inde­xed links or take them out of the index.

Note: It may take some time for search engi­nes (Goog­le, Bing…) to update your index.

I hope this artic­le was hel­pful for you. Feel free to lea­ve us a com­ment if you have any ques­ti­ons.

88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Hi Marc here. I’m the foun­der of Forge12 Inter­ac­ti­ve and have been pas­sio­na­te about buil­ding web­sites, online stores, appli­ca­ti­ons and SaaS solu­ti­ons for busi­nesses for over 20 years. Befo­re foun­ding the com­pa­ny, I alre­a­dy work­ed in publicly lis­ted com­pa­nies and acqui­red all kinds of know­ledge. Now I want to pass this know­ledge on to my cus­to­mers.

Hast du eine Fra­ge? Hin­ter­lass bit­te einen Kom­men­tar