Fixing image issue in posts

Issue

For article collection site, many articles are copied from other websites. Very often, images were not displayed.

Reason

Some image servers switching their protocol between http and https.

Solution

1. Add a general function imgError. You could add it from ‘Custom CSS & JS’ plugin in it was installed.

function imgError(image) {
    image.onerror = "";
    if(image.src.startsWith('http:')) image.src=image.src.replace(/^http:\/\//i, 'https://');
    if(image.src.startsWith('https:')) image.src=image.src.replace(/^https:\/\//i, 'http://');
}

2. Add onerror event to all img tags.

UPDATE wp_posts set post_content=replace(post_content,'<img ','<img onerror="imgError(this);" ');

Done.

TODO: add js script to add onerror event to all img tags dynamically.

Leave a Reply