-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordpressfunc.php
58 lines (50 loc) · 2.15 KB
/
wordpressfunc.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
/**
* add this snippet to your function.php in your theme directory
* ex: LazyContent(content());
* ex: LazyContent('your custom html block, acf, html..);
*/
function LazyContent($content)
{
$dom = new \DOMDocument('1.0', 'UTF-8');
libxml_use_internal_errors(true);
$dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
/**
* [IFRAMES] Transform all iframes youtube.com to youtube-nocookies.com and use Vanilla Lazyload JS or loading lazy !
* if you need others links add elseif youtube.be..
*/
$iframes = $dom->getElementsByTagName('iframe');
foreach ($iframes as $iframe) {
$src = $iframe->getAttribute('src');
if (strpos($src, '//www.youtube.com') !== false) {
$newSrc = str_replace('//www.youtube.com/', '//www.youtube-nocookie.com/', $src);
} elseif (strpos($src, '//youtube.com') !== false) {
$newSrc = str_replace('//youtube.com/', '//www.youtube-nocookie.com/', $src);
} else {
continue;
}
// if you use a vanilla lazyload js or comment this
$iframe->setAttribute('data-src', $newSrc);
$iframe->removeAttribute('src');
$iframe->setAttribute('class', trim($iframe->getAttribute('class') . ' lazy'));
// native browsers
$iframe->setAttribute('loading', 'lazy');
}
/**
* [Pictures] Vanilla Lazyload JS or Browser loading lazy
*/
$images = $dom->getElementsByTagName('img');
foreach ($images as $img) {
$src = $img->getAttribute('src');
if ($src) {
// vanilla lazyload js method
$img->setAttribute('data-src', $src);
$img->removeAttribute('src');
$img->setAttribute('class', trim($img->getAttribute('class') . ' lazyload androModal'));
// for native browsers
$img->setAttribute('loading', 'lazy');
}
}
return $dom->saveHTML();
}