The filters you are trying to use run on image insertion, so it is not possible to swap all the images already present in your posts using these filters. It should work, however, if you intend to change to img
tags from now on.
The filter the_content
, however, is applied to the post after it is retrieved from the database and before displaying it to screen. I believe that, in order to make a change to your existing posts without reinserting the images, you could use this filter.
You can parse the_content
using the PHP DOMDocument class. When it comes to HTML parsing in PHP, do not use regex.
I wrote a sample function for what you want to do, it’s a bit verbose in order to explain the passages. Feel free to tweak it at will.
<?php
function foresight_hires_img_replace($the_content) {
// Create a new istance of DOMDocument
$post = new DOMDocument();
// Load $the_content as HTML
$post->loadHTML($the_content);
// Look up for all the <img> tags.
$imgs = $post->getElementsByTagName('img');
// Iteration time
foreach( $imgs as $img ) {
// Let's make sure the img has not been already manipulated by us
// by checking if it has a data-src attribute (we could also check
// if it has the fs-img class, or whatever check you might feel is
// the most appropriate.
if( $img->hasAttribute('data-src') ) continue;
// Also, let's check that the <img> we found is not child of a <noscript>
// tag, we want to leave those alone as well.
if( $img->parentNode->tagName == 'noscript' ) continue;
// Let's clone the node for later usage.
$clone = $img->cloneNode();
// Get the src attribute, remove it from the element, swap it with
// data-src
$src = $img->getAttribute('src');
$img->removeAttribute('src');
$img->setAttribute('data-src', $src);
// Same goes for width...
$width = $img->getAttribute('width');
$img->removeAttribute('width');
$img->setAttribute('data-width', $width);
// And height... (and whatever other attribute your js may need
$height = $img->getAttribute('height');
$img->removeAttribute('height');
$img->setAttribute('data-height', $height);
// Get the class and add fs-img to the existing classes
$imgClass = $img->getAttribute('class');
$img->setAttribute('class', $imgClass . ' fs-img');
// Let's create the <noscript> element and append our original
// tag, which we cloned earlier, as its child. Then, let's insert
// it before our manipulated element
$no_script = $post->createElement('noscript');
$no_script->appendChild($clone);
$img->parentNode->insertBefore($no_script, $img);
};
return $post->saveHTML();
}
add_filter('the_content', 'foresight_hires_img_replace');
?>
I didn’t test it specifically with WordPress, but I tested it with a sample post output and it should work.