• Resolved stephencottontail

    (@stephencottontail)


    I’m working on a new theme and I’d like for translators to be able to deactivate Google fonts if the fonts don’t support the translator’s language. I’ve got this function:

    function mytheme_fonts_url() {
      $fonts_url = '';
    
      /* translators: If there are characters in your language that aren't supported by Titillium Web, translate this to 'off'. Do not translate this into your own language. */
      $titillium = _x( 'on', 'Use Titillium Web font: on or off', 'mytheme' );
    
      /* translators: If there are characters in your language that aren't supported by PT Sans, translate this to 'off'. Do not translate this into your own language. */
      $pt_sans = _x( 'on', 'Use PT Sans font: on or off', 'mytheme' );
    
      if ( 'off' !== $titillium || 'off' !== $pt_sans ) :
        $font_families = array();
    
        if ( 'off' !== $titillium ) :
          $font_families[] = 'Titillium+Web:400,400italic,700,700italic';
        endif;
    
        if ( 'off' !== $pt_sans ) :
          $font_families[] = 'PT+Sans:400,400italic,700,700italic';
        endif;
    
        $query_args = array(
          'family' => urlencode( implode( '|', $font_families ) ),
          'subset' => urlencode( 'latin,latin-ext' ),
        );
    
        $fonts_url = add_query_arg( $query_args, '//fonts.googleapis.com/css' );
        return $fonts_url;
      endif;
    }

    And I load the fonts like this:

    function mytheme_scripts() {
      wp_enqueue_style( 'mytheme-google-fonts', mytheme_fonts_url(), array(), null );
    }
    add_action( 'wp_enqueue_scripts', 'mytheme_scripts' );

    However, whenever I load the new theme, I get a 400 error when trying to load the Google fonts. What am I missing?

Viewing 3 replies - 1 through 3 (of 3 total)
  • CrouchingBruin

    (@crouchingbruin)

    Try not converting the strings with urlencode.

    Thread Starter stephencottontail

    (@stephencottontail)

    Thanks for the reply. It seems to work now. Why would urlencode() make a difference?

    CrouchingBruin

    (@crouchingbruin)

    I’m not sure. When I inserted your code into one of my child themes, I noticed that the link that was created looked different than another Google Fonts link, which didn’t have the character encoding, so I manually changed all of the escape characters on yours and it worked. Maybe Google doesn’t decode the escape characters when reading the font info.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Conditional loading Google fonts’ is closed to new replies.