Skip to content

Instantly share code, notes, and snippets.

@bikubi
Created March 13, 2019 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bikubi/fb2456c68899490a0c793b2749f44f97 to your computer and use it in GitHub Desktop.
Save bikubi/fb2456c68899490a0c793b2749f44f97 to your computer and use it in GitHub Desktop.
hack to inject better sizes attribute into WordPress Gutenberg Gallery Block
<?php
/* Not really recommended, very dangerous. Will change entities.
* Adjust the xpath query & sizes to your needs.
*/
add_filter('the_content', function ($content) {
try {
$preamble = '<?xml encoding="utf-8" ? >';
$doc = new DOMDocument();
$doc->preserveWhiteSpace = true;
$doc->substituteEntities = false;
$doc->loadHTML($preamble.$content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOWARNING | LIBXML_NOERROR);
$xpath = new DOMXpath($doc);
$imgs = $xpath->query('//ul[contains(@class, "wp-block-gallery") and contains(@class, "columns-2")]//figure//img'); // adjust
if (!$imgs) {
// better not mess around
return $content;
}
else {
foreach ($imgs as $img) {
$img->setAttribute('sizes', '(max-width: 781px) 50vw, 344px'); // adjust
}
}
return str_replace($preamble, '', $doc->saveHTML());
}
catch (Exception $e) {
// give up
return $content;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment