Created
March 13, 2019 11:37
-
-
Save bikubi/fb2456c68899490a0c793b2749f44f97 to your computer and use it in GitHub Desktop.
hack to inject better sizes attribute into WordPress Gutenberg Gallery Block
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
<?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