How to fix broken images in WordPress?

Image Not Found

Nothing exists forever — including those images that you inserted in your blogposts from various external sources. Those who have been blogging for a long time now know the pain of such broken image links. Due to corrupt files, incorrect links, expired domains, deleted resources or whatever — your WordPress site can occasionally yield 404-errors on images — leading to negative SEO and poor reading experience.

One solution that exists — is to replace those image links with proper ones — which is a big headache.

But there exists a simple Javascript snippet which you can add to your site’s header and replace all broken images with a default one – in a jiffy.

Let’s assume that the image that you want to use as replacement of broken images is located at /wp-content/uploads/2018/08/replace.png, you can add this Javascript to your WordPress blog’s header:

$('img').error(function(){
$(this).attr('src', '/wp-content/uploads/2018/08/replace.png');
});

If you don’t know how to do so, you can use a plugin like Header and Footer Scripts to insert your custom javascript arguments.

Alternatively, you can just place this PHP code snippet in your theme’s functions.php file, anywhere between <?php and ?> :

function imgReplace() { ?>
<script>
  $('img').error(function(){
$(this).attr('src', '/wp-content/uploads/2018/08/replace.png');
});
</script>
<?php }
add_action( 'wp_head', 'imgReplace' );

This is a totally safe practice and won’t do any harm if your site has no broken images at all.

Default image
Gaurav Tiwari
Gaurav Tiwari is a professional graphic & web designer from New Delhi, India. gauravtiwari.org is his personal space where he writes on blogging, digital marketing, content writing, learning and business growth. Gaurav has contributed in developing more than 325 brands worldwide and while you are reading this, he's busy building a couple more.

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply