danyaneh
10/18/2017 - 2:21 AM

WordPress Google Fonts functions

WordPress Google Fonts functions

<?php
/**
 * Register custom fonts. Allow Translator to toggle google fonts on and off.
 */
function text_domain_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', 'Sample font: on or off', 'pccit' );
    $secondary = _x( 'on', ' Sample font: on or off', 'pccit' );
    $font_families = array();
    if( 'off' !== $primary){
        $font_families[] = 'Droid Serif:400,700';
    }
    if( 'off' !== $secondary){
        $font_families[] = 'Open Sans:400,700';
    }
    if ( in_array( 'on', array($primary, $secondary) ) )  {
        $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 );
}
/**
 * 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' );