Tuesday, 27 August 2013

Create HTML elements with php

Create HTML elements with php

I have a image heavy wordpress site.
To help with loading I'm using lazy loading.
The lazyload plugin requires the img url in a 'data-original' attribute.
I'm changing the img element using the function to add the image url to
'data-original' and the placeholder to the 'src'
function add_lazyload($content) {
$dom = new DOMDocument();
@$dom->loadHTML($content);
foreach ($dom->getElementsByTagName('img') as $node) {
$oldsrc = $node->getAttribute('src');
$node->setAttribute("data-original", $oldsrc );
$newsrc =
''.get_template_directory_uri().'/library/images/nothing.gif';
$node->setAttribute("src", $newsrc);
//create img tag
$element = $dom->createElement("img");
$dom->appendChild($element);
}
$newHtml = $dom->saveHtml();
return $newHtml;
}
add_filter('the_content', 'add_lazyload');
The lazyloading is working but I wanted to add a non javascript fall back
Is it possible with the above function to create a new 'img' element using
the 'src' from the original 'img'
so the new 'img' element would look like this
<noscript><img src="img/example.jpg" width="640" heigh="480"></noscript>

No comments:

Post a Comment