How to Hide Broken Images in WordPress Blogs

The Problem:

After migrating the blog from the old website to the new one, I noticed that some of the posts had a broken first image, which also happened to be the featured image for those blogs. There was an additional challenge in that no unique CSS ID was assigned to these images, and checking over 1800 blog posts was not an ideal solution, etc…

The Solution:

After some exploration and trial, I stumbled upon an effective JavaScript solution to tackle this issue. By implementing a few lines of code, I was able to hide the broken images that didn’t start with the website domain or “http” or “https.”.

How It Works:

The JavaScript code I used scans the images inside a specific class that I assigned to the content widget (in my case, “.mis-blog-post“), then checks each image’s URL. If the URL is broken (i.e., the image doesn’t load) or doesn’t start with website domain or “http” or “https,” the script hides the image. This simple yet powerful solution eliminated the annoyance of broken images and provided a cleaner and more professional appearance for the blog.

Step #1:

Screen Shot 2023 07 20 at 5.36.35 PM

Step #2:

Inject the following code using the script organizer, and read the comments to understand what each piece of code does.

				
					// Function to check if a URL is valid
function isValidUrl(url) {
  // Create an anchor element to parse the URL
  const anchor = document.createElement("a");
  anchor.href = url;

  // Check if the hostname (domain name) is empty or not the same as the current domain
  return anchor.hostname !== "" && anchor.hostname !== window.location.hostname;
}

// Function to handle broken images and hide invalid links
function handleBrokenImagesAndInvalidLinks() {
  // Get all the images inside the ".mis-blog-post" class
  const images = document.querySelectorAll(".mis-blog-post img");

  // Loop through each image and handle broken images
  for (let i = 0; i < images.length; i++) {
    const image = images[i];

    // Check if the image URL is empty, starts with your website domain, or starts with "http" or "https"
    // If not, hide the image
    if (
      !image.complete ||
      image.naturalWidth === 0 ||
      (!image.src.startsWith(window.location.origin) &&
        !image.src.startsWith("http://") &&
        !image.src.startsWith("https://"))
    ) {
      image.style.display = "none";
    }
  }
}

// Call the function to handle broken images and invalid links when the page has loaded
window.addEventListener("load", handleBrokenImagesAndInvalidLinks);

				
			

That’s it. hope you find value in it!

Happy Developing! ✌️

Credit: Credit goes to ChatGPT for providing the working code after several prompts 🤩