By default, WordPress will create new pages for your images and other attachments.
If you’re a standard WordPress user, you might want to redirect WordPress attachment pages to the original post to where the file was attached to.
Simply copy and add the function to your functions.php file
add_action( 'template_redirect', 'wpsites_attachment_redirect' );
function wpsites_attachment_redirect(){
global $post;
if ( is_attachment() && isset($post->post_parent) && is_numeric($post->post_parent) && ($post->post_parent != 0) ) :
wp_redirect( get_permalink( $post->post_parent ), 301 );
exit();
wp_reset_postdata();
endif;
}
Code Snippet Explanation
This code snippet contains a WordPress function that is hooked to the template_redirect action. This action is triggered before the template files are loaded and the wp action hook has been fired.
The function wpsites_attachment_redirect() first checks if the current post is an attachment and if it has a parent post. If both conditions are met, it redirects the user to the parent post using the wp_redirect() function and exits the script. The 301 status code passed as a second argument to the wp_redirect() function indicates that the redirection is permanent.
The wp_reset_postdata() function is called at the end, but it has no effect since the script has already exited.
This code is intended to redirect users who visit an attachment page (e.g., an image or a PDF file) to the post or page where the attachment is inserted instead of displaying the attachment page itself.
This function can be useful if you want to keep users on your website and avoid having them download the attachment directly.
Redirect Attachment Pages to the Resources
Add this to your functions.php file if you want to redirect visitors to the resources.
add_action( 'template_redirect', 'wpsites_attachment_redirect' );
function wpsites_attachment_redirect(){
global $post;
if ( is_attachment() && isset($post->post_parent) && is_numeric($post->post_parent) && ($post->post_parent != 0) ) :
$attachment_url = wp_get_attachment_url( $post->ID );
wp_redirect( $attachment_url, 301 );
exit();
wp_reset_postdata();
endif;
}
More Code Snippets
There are more code snippets where this came from:
- How to Create a Table of Content without a Plugin
- How to Disable Heartbeat in WordPress
- How to Remove Global Styles in WordPress
- How to Disable Comments in WordPress
- How to Disable Rest API and Rest API Links
- How to Disable Self Pingbacks in WordPress
- How to Disable RSS Feeds and RSS Feed Links in WordPress