Created
August 19, 2024 10:11
-
-
Save dkjensen/d09b7c5e3f817cc2218fae06c3a483d2 to your computer and use it in GitHub Desktop.
Preload WordPress theme.json custom fonts
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 | |
/** | |
* 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(); | |
$type = null; | |
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 ) | |
); | |
} | |
} | |
} | |
} | |
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