Replace image attributes for lazyload plugin (data-src)

Question

I want to apply jquery lazyload plugin. For this to work I have to create a new attribute which is data-src place there the src value and then replace the src value with a specific value '...nothing.gif'.
I found a solution on wordpress.org support

This is my adapted code –

function add_lazyload($content) 
{
    global $post;
    $search = '/src="([^s]+(?=.(bmp|gif|jpeg|jpg|png)).2)"/';
    $content = replacer($content, $search, '/src/', 'data-original');
    $search = '/img class="/';
    $content = replacer($content, $search, '/class="/', 'class="lazy ');
    $search = '/alt/';
    $content = replacer($content, $search, '/alt/', 'src="'.get_template_directory_uri().'/library/images/nothing.gif"');
    return $content;
}

function replacer($src, $search, $find, $replace)
{
    preg_match_all($search, $src, $result, PREG_OFFSET_CAPTURE);
    foreach($result[0] as $entry)
    {
        $org = $entry[0];
        $rep = preg_replace($find, $replace, $entry[0]);
        $org = "/" .str_replace(array("=",":","/",".","-","_",'"',"'"," "),     array("=",":","/",".","-","_",'"',"'"," "), $org). "/";
        $src = preg_replace($org, $rep, $src);
    }
return $src;
}

add_filter('the_content', 'add_lazyload');

The problem with this code is that it replaces every alt string (for example in a paragraph) with .../library/images/nothing.gif, not just the alt image attribute.

Does anyone know how to solve this?

0
, , Alvaro 3 years 2020-06-07T23:11:45-05:00 0 Answers 109 views 0

Leave an answer

Browse
Browse