Skip to content

Instantly share code, notes, and snippets.

@ivorpad
Last active September 19, 2024 12:39
Show Gist options
  • Save ivorpad/b5cff9c3d597d2764295 to your computer and use it in GitHub Desktop.
Save ivorpad/b5cff9c3d597d2764295 to your computer and use it in GitHub Desktop.
<?php
// Wrong 1
<link href='http://fonts.googleapis.com/css?family=Cabin:400,500|Open+Sans:300,400,700|Oswald:300,400,700|PT+Sans+Caption:400,700' rel='stylesheet' type='text/css'>
// Wrong 2
/**
* Enqueue the Open Sans font.
*/
function mytheme_fonts() {
$protocol = is_ssl() ? 'https' : 'http';
wp_enqueue_style( 'mytheme-opensans', "$protocol://fonts.googleapis.com/css?family=Open+Sans" );}
add_action( 'wp_enqueue_scripts', 'mytheme_fonts' );
// ## Correct
/**
* Register custom fonts.
*/
function my_theme_fonts_url() {
$fonts_url = '';
$libre_franklin = _x( 'on', 'libre_franklin font: on or off', 'twentyseventeen' );
if ( 'off' !== $libre_franklin ) {
$font_families = array();
$font_families[] = 'Libre Franklin:300,300i,400,400i,600,600i,800,800i';
$query_args = array(
'family' => urlencode( implode( '|', $font_families ) ),
'subset' => urlencode( 'latin,latin-ext' ),
);
$fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css' );
}
return esc_url_raw( $fonts_url );
}
/**
* Enqueue scripts and styles.
*/
function my_theme_custom_scripts() {
// Add custom fonts, used in the main stylesheet.
wp_enqueue_style( 'my-theme-fonts', my_theme_fonts_url(), array(), null );
}
add_action( 'wp_enqueue_scripts', 'my_theme_custom_scripts' );
function my_theme_resource_hints( $urls, $relation_type ) {
if ( wp_style_is( 'my-theme-fonts', 'queue' ) && 'preconnect' === $relation_type ) {
$urls[] = array(
'href' => 'https://fonts.gstatic.com',
'crossorigin',
);
}
return $urls;
}
add_filter( 'wp_resource_hints', 'my_theme_resource_hints', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment