Hi 🙂
You could try editing your theme’s 404.php file to include something like the following at the top:
<?php
// Test for media lookup
$address = $_SERVER['REQUEST_URI'];
if ( preg_match( "/wp-content\/uploads\//", $address ) )
{
// Redirect or load template here
die( "MEDIA DOESN’T EXIST" );
}
?>
Note, I’ve used the die() function above, but you can switch it to a redirect or get template part, or whatever. Hope this helps.
Hi @corenominal,
Thankyou very much for your answer.
Since I don’t have experience with php, can you please tell me how to redirect to some page let’s say somewebsite.com/media-not-exist page.
I mean part of code required to place there.
Sure, WP has a function for that, you could try something like:
<?php
// Test for media lookup
$address = $_SERVER['REQUEST_URI'];
if ( preg_match( "/wp-content\/uploads\//", $address ) )
{
// Redirect or load template here
wp_redirect( 'https://somewebsite.com/media-not-exist page' );
exit;
}
?>
@corenominal Thankyou for reply,
Can I make a new php file like mediaerror.php and paste this code there, would it work?
And where to save this file(directory)
-
This reply was modified 3 years, 1 month ago by itsboss10.
The 404 Not Found template (404.php in your theme directory if you have one, it is not a required theme file) is used when WordPress cannot find a post, page or file that matches the query. Ideally the code should be placed in this file. That said, I have no idea what theme or plugins you are using, so it might not work for you.
Note, in your original post you state:
Now since file doesn’t exist it redirects to Error 404 page.
This isn’t quite accurate. The 404.php template file is called/loaded, not redirected to. Hope this makes sense? Happy to continue the conversation if you have more questions.
Thanks for replying.
This does makes sense, so I should place this code in 404.php file…
Can you tell if I can add my html code with this code and how?
I mean what is better: to redirect to media does not exist page or adding html code(if it supports, I don’t really know).
Personally, I would load a template part. If you only have two conditions, then it should look something like:
<?php
// Test for media lookup
$address = $_SERVER['REQUEST_URI'];
if ( preg_match( "/wp-content\/uploads\//", $address ) )
{
// Load media missing template/message
get_template_part( '404-missing-media-template' );
}
else
{
// Load regular 404 template/message
get_template_part( '404-template' );
}
?>
As you are not redirecting, the above could sit anywhere within your 404.php file, where you want the message to be displayed. Note, you will need to create two more files in your theme directory:
- 404-missing-media-template.php – containing “MEDIA DOESN’T EXIST” message
- 404-template.php – containing regular 404 message