Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sabrina-zeidan/30127a9b5b456b986afea8f8c19a0fa2 to your computer and use it in GitHub Desktop.
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]
//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