Skip to content

Instantly share code, notes, and snippets.

@JacobDB
Created August 30, 2023 14:34
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 JacobDB/ceb360b6e08ef94f3359da55e12a519b to your computer and use it in GitHub Desktop.
Save JacobDB/ceb360b6e08ef94f3359da55e12a519b to your computer and use it in GitHub Desktop.
Send preload headers for WordPress CSS files
<?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