Switch external image for index page and 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.

e.g. https://i2.kknews.cc

Solution

1. Index page

post block html output is from wp_kses_post( $apostrophe_2_post_thumbnail )

So, In content.php file under child theme, replace echo wp_kses_post( $apostrophe_2_post_thumbnail ); with

echo str_replace('<img ','<img onerror="imgError(this);" ',wp_kses_post($apostrophe_2_post_thumbnail));

2. Post page

In plugin ad_after function in ad-inserter.php add following code:

$content = str_replace('<img ','<img onerror="imgError(this);" ',$content);

In Custom CSS & JS add script, this script will be added to both index and post pages:

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://');
}

This is improved version of “Fixing image issue in posts“.

360 total views, 5 views today

Author: Albert

Leave a Reply