Created
August 30, 2023 14:34
-
-
Save JacobDB/ceb360b6e08ef94f3359da55e12a519b to your computer and use it in GitHub Desktop.
Send preload headers for WordPress CSS files
This file contains hidden or 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 | |
/** | |
* Preload styles | |
* | |
* @return void | |
*/ | |
function mytheme_preload_styles(): void { | |
global $wp_styles; | |
if ($wp_styles) { | |
$site_url = get_site_url(); | |
$urls = []; | |
foreach ($wp_styles->queue as $style) { | |
$data = $wp_styles->registered[$style]; | |
if ($data->src && ! isset($data->extra["conditional"]) && ! (isset($data->args) && $data->args !== "all")) { | |
$src = $data->src; | |
if (strpos($src, $site_url) !== false) { | |
$src = str_replace($site_url, "", $src); | |
} | |
if ($data->ver) { | |
$src .= "?ver={$data->ver}"; | |
} | |
$urls[] = "<{$src}>; rel=preload; as=style"; | |
} | |
} | |
if ($urls) { | |
header("link: " . implode(", ", $urls)); | |
} | |
} | |
} | |
add_action("send_headers", "mytheme_preload_styles", 1, 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment