Entering a child page that does not exist will redirect to the image attachment page, specifically, the image attachment with the same slug.
Say, entering example/cars/volvo-car/
will redirect to the image attachment page with the URL example/volvo-car/
.
The volvo-car
image attachment's permalink reflects the image name on initial upload, but even after I changed the attachment's slug to something different like volvo-car-image
the non-existent child page still redirects to it instead of firing the 404 error page.
I can't find any entries in the database that would cause the redirect. I also tried it with different websites on different servers, but still getting the same behavior.
How can I fix it or stop WordPress from doing it?
Another thing I have discovered is that the parent page doesn't have to exist before this happens. As long as you add the image attachment URL's slug after the parent slug, it would still redirect to the attachment page like example/fasdfwefa/image-slug
.
Entering a child page that does not exist will redirect to the image attachment page, specifically, the image attachment with the same slug.
Say, entering example/cars/volvo-car/
will redirect to the image attachment page with the URL example/volvo-car/
.
The volvo-car
image attachment's permalink reflects the image name on initial upload, but even after I changed the attachment's slug to something different like volvo-car-image
the non-existent child page still redirects to it instead of firing the 404 error page.
I can't find any entries in the database that would cause the redirect. I also tried it with different websites on different servers, but still getting the same behavior.
How can I fix it or stop WordPress from doing it?
Another thing I have discovered is that the parent page doesn't have to exist before this happens. As long as you add the image attachment URL's slug after the parent slug, it would still redirect to the attachment page like example/fasdfwefa/image-slug
.
- Firstly have you cleared your cache? – Lewis Commented Jan 24, 2019 at 20:38
1 Answer
Reset to default 0If I understood you correctly you want to disable all attachment pages and redirect them to 404 page. Place this code in functions.php and try it again.
add_action( 'template_redirect', 'redirect_media_to_404' );
function redirect_media_to_404() {
if ( is_attachment() ) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 );
exit();
}
}