Skip to content

Instantly share code, notes, and snippets.

@daniloparrajr
Last active May 26, 2020 12:20
Show Gist options
  • Save daniloparrajr/826063b377f94151c7bc54783873c752 to your computer and use it in GitHub Desktop.
Save daniloparrajr/826063b377f94151c7bc54783873c752 to your computer and use it in GitHub Desktop.
WordPress Google Fonts functions
<?php
/**
* Register custom fonts. Allow Translator to toggle google fonts on and off.
*/
function theme_slug_fonts_url() {
$fonts_url = '';
/*
* Translators: If there are characters in your language that are not
* supported by Sample Font and Sample Font, translate this to 'off'. Do not translate
* into your own language.
*/
$primary = _x( 'on', 'Roboto font: on or off', 'text_domain' );
$secondary = _x( 'on', 'Open Sans font: on or off', 'text_domain' );
$font_families = array();
if( 'off' !== $primary){
$font_families[] = 'Roboto:wght@400;700';
}
if( 'off' !== $secondary){
$font_families[] = 'Open+Sans:wght@400;600';
}
if ( in_array( 'on', array($primary, $secondary) ) ) {
$query_args = array(
'family' => urlencode( implode( '|', $font_families ) ),
'subset' => urlencode( 'latin,latin-ext' ),
'display' => 'swap'
);
$fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css2' );
}
return esc_url_raw( $fonts_url );
}
/**
* Add preconnect for Google Fonts.
*
* @since Your Theme 1.0
*
* @param array $urls URLs to print for resource hints.
* @param string $relation_type The relation type the URLs are printed.
* @return array $urls URLs to print for resource hints.
*/
function text_domain_resource_hints( $urls, $relation_type ) {
if ( wp_style_is( 'text-domain-fonts', 'queue' ) && 'preconnect' === $relation_type ) {
$urls[] = array(
'href' => 'https://fonts.gstatic.com',
'crossorigin',
);
}
return $urls;
}
add_filter( 'wp_resource_hints', 'text_domain_resource_hints', 10, 2 );
/**
* Add this to your existing wp_enqueue_scripts action: see example below
*/
function text_domain_scripts() {
wp_enqueue_style( 'text-domain-fonts', text_domain_fonts_url() );
}
add_action( 'wp_enqueue_scripts', 'text_domain_scripts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment