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 if 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.

<img onerror="imgError(this);" src= ...>

Modify existing posts to apply this solution:

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.

355 total views, 1 views today

Author: Albert

One comment

Leave a Reply