Created
December 14, 2024 14:46
-
-
Save dkjensen/54865973a25300d6db20b095dbe80ada to your computer and use it in GitHub Desktop.
Preload WordPress theme.json fonts
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 fonts. | |
* | |
* @return void | |
*/ | |
function preload_fonts() { | |
$fonts = \WP_Font_Face_Resolver::get_fonts_from_theme_json(); | |
if ( empty( $fonts ) ) { | |
return; | |
} | |
foreach ( $fonts as $font ) { | |
if ( ! is_array( $font ) || empty( $font ) ) { | |
continue; | |
} | |
foreach ( $font as $variation ) { | |
$src = $variation['src'] ?? array(); | |
if ( empty( $src ) ) { | |
continue; | |
} | |
if ( ! is_array( $src ) ) { | |
$src = array( $src ); | |
} | |
foreach ( $src as $uri ) { | |
$extension = pathinfo( $uri, PATHINFO_EXTENSION ); | |
if ( ! $extension ) { | |
continue; | |
} | |
printf( | |
'<link rel="preload" href="%s" as="font" type="font/%s" crossorigin="anonymous">', | |
esc_url( $uri ), | |
esc_attr( $extension ) | |
); | |
echo PHP_EOL; | |
} | |
} | |
} | |
} | |
add_action( 'wp_head', __NAMESPACE__ . '\preload_fonts' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment