Regex to alter img attributes in Wordpress Filter
I have a custom theme I've developed for a photographer client and need to implement lazy-loading of the images so that the blog loads faster as it is horribly slow due to the amount of images he currently has, even when only showing five posts. To do this I'm using the JAIL jquery plugin but I need to be able to modify the image tags for it to work properly.. basically I have to replace the src attribute with a placeholder and set a data-href attribute to the source url. I cannot seem to find a resolution that works properly inside of a wordpress filter, I'm basically filtering the_content() h开发者_运维技巧ook in the posts.. does anyone know how I could accomplish this?
The standard Stackoverflow cliche for these questions is that you should use a DOM parser. Which is actually correct, but not quite feasible (performance) for output manipulation.
To accomplish what you want you could try:
$html = preg_replace_callback(
'#(<img\s[^>]*src)="([^"]+)"#',
"callback_img", $html);
Then define a callback like this:
function callback_img($match) {
list(, $img, $src) = $match;
return "$img=\"placeholder\" data-href=\"$src\" ";
}
Note that this regex is only workable if all your image links follow this scheme consistently (they all should be using double quotes for example).
精彩评论