Created
August 22, 2022 00:50
-
-
Save sabrina-zeidan/30127a9b5b456b986afea8f8c19a0fa2 to your computer and use it in GitHub Desktop.
Modify any specific element knowing its parent class via WP Rocket buffer [WordPress]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Add missing width and height to the specific img to avoid layout shift, knowing its parent element class | |
//Or modify anything at all via WP Rocket buffer | |
add_filter('rocket_buffer','sz_wprocket_modify_buffer', 10); | |
function sz_wprocket_modify_buffer ($buffer){ | |
$dom = new DOMDocument(); | |
$dom->loadHTML($buffer); | |
$xpath = new DOMXPath($dom); | |
$expression = './/div[contains(concat(" ", normalize-space(@class), " "), " mypic ")]'; //tag and class here | |
foreach ($xpath->evaluate($expression) as $parentelement) { | |
foreach ($parentelement->getElementsByTagName('img') as $tag) { //targeting img inside the parent tag | |
// $tag->setAttribute('szattribute', 'szvalue'); //or add any other attribute | |
$tag->setAttribute('width', ''); | |
$tag->setAttribute('height', ''); | |
} | |
} | |
$buffer = $dom->saveHtml(); | |
return $buffer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment