solutionweb

WordPress Common Errors and Solutions

How to disable url address of picture attachment page in wordpress website

When wordpress publishes and updates articles, we always upload pictures or video attachments to the media library.

But you will find that uploading attachments in wordpress background will automatically generate an attachment page. As shown in the figure below:

How to disable url address of picture attachment page in wordpress website

This page has no other valuable text content, only an attachment name and a picture or video. This kind of page is a low-quality page in the eyes of search engines, because there is no text content, which seriously affects the search engine keyword ranking of the website. So how to solve this problem? How to disable wordpress attachment pages?

Let’s share with you a method:
We can ban this attachment page by adding the following code to the current theme functions.php file:

//Disable WordPress attachment page
function wpb_redirect_attachment_to_post() {
if ( is_attachment() ) {
global $post;
if( empty( $post ) ) $post = get_queried_object();
if ($post->post_parent) {
$link = get_permalink( $post->post_parent );
wp_redirect( $link, ‘301’ );
exit();
}
else {
// What to do if parent post is not available
wp_redirect( home_url(), ‘301’ );
exit();
}
}
}
add_action( ‘template_redirect’, ‘wpb_redirect_attachment_to_post’ );
This will jump to the corresponding article page when accessing the attached attachment. If there is no attachment attached to the article, it will automatically jump to the home page. This only disables the attachment wordpress page, not the attachment itself. The attachment itself can still be accessed normally.

Back to top