Last active
November 3, 2021 10:14
-
-
Save markhowellsmead/92cab736ff577805820bf0263f11984f to your computer and use it in GitHub Desktop.
Replace the CSS Custom Properties assignment to BODY onto the :root element
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 | |
/** | |
* WordPress Core currently assigns the CSS Custom Properties | |
* to the HTML body element, so CSS Custom Properties assigned | |
* to :root cannot access them. This is defined by WP_Theme_JSON::ROOT_BLOCK_SELECTOR | |
* which (at the date of writing) cannot be hooked or modified | |
* by external means. | |
* | |
* This script replaces the assignment from body {…} to :root {…} | |
* using PHP XPath on the HTML generated within wp_head. | |
* | |
* See https://github.com/WordPress/gutenberg/issues/35840 for discussion. | |
* | |
* mark@sayhello.ch 2.11.2021 | |
*/ | |
/** | |
* Open an output buffer in order to temporarily store the content of wp_head | |
* | |
* @return void | |
*/ | |
function css_properties_start_head_buffer(){ | |
ob_start(); | |
} | |
/** | |
* Parse the contents of the wp_head output buffer. | |
* Replace the body { definition inside the style tag | |
* with the ID global-styles-inline-css with :root { | |
* | |
* @return string | |
*/ | |
function css_properties_end_head_buffer(){ | |
$head_html = ob_get_clean(); | |
if (!empty($head_html)) { | |
libxml_use_internal_errors(true); | |
$document = new \DOMDocument(); | |
$document->loadHTML(mb_convert_encoding($head_html, 'HTML-ENTITIES', 'UTF-8')); | |
$xpath = new \DOMXPath($document); | |
$style_tag = $xpath->query('//style[@id="global-styles-inline-css"]'); | |
if ($style_tag instanceof \DOMNodeList && $style_tag->length > 0) { | |
foreach ($style_tag as $global_styles) { | |
$global_styles->nodeValue = preg_replace('/^body\{/', chr(10) . ':root, body {', trim($global_styles->nodeValue) . chr(10)); | |
} | |
$head_html = $document->saveHtml($document->getElementsByTagName('html')[0]->getElementsByTagName('head')->item(0)); | |
} | |
} | |
echo $head_html; | |
} | |
add_action('wp_head', 'css_properties_start_head_buffer', 0); | |
add_action('wp_head', 'css_properties_end_head_buffer', PHP_INT_MAX); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment