Last active
November 11, 2020 07:30
-
-
Save mikeott/5b81fd46b9475e86bcf8d81537ef4b37 to your computer and use it in GitHub Desktop.
List all Google fonts (for use in a WordPress plugin)
This file contains hidden or 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 | |
/* | |
You'll need to get an API key. | |
Go to https://developers.google.com/fonts/docs/developer_api and scroll down to the 'Gey a Key' button. | |
*/ | |
$api_key = "your-key-here"; | |
$google_font = isset($options['google_font']) ? $options['google_font'] : ''; | |
$url = 'https://www.googleapis.com/webfonts/v1/webfonts?key=' . $api_key; | |
$args = array( | |
'timeout' => 15, | |
'redirection' => 10, | |
'httpversion' => '1.0', | |
); | |
$response = wp_remote_get( $url, $args ); | |
?> | |
<?php if ( ! is_wp_error( $response ) ) : ?> | |
<?php $body = json_decode( $response['body'] ); ?> | |
<?php $font_list = $body->items; ?> | |
<select name="stormbox_settings[google_font]" class="font-selection"> | |
<option value=""></option> | |
<?php foreach ( $font_list as $font ) : ?> | |
<option value="<?php echo esc_attr( $font->family ) ?>" <?php if ( $font->family == $google_font) { echo 'selected="selected"'; } ?>> | |
<?php echo esc_html( $font->family ) ?> | |
</option> | |
<?php endforeach; ?> | |
</select> | |
<?php else : ?> | |
The Google Fonts API is possibly unavailable. | |
<?php endif; ?> | |
<!--/ The following is not required, but you'll need jQuery if you want to use it. /--> | |
<br /> | |
<a href="" class="font-details" target="_blank" rel="noopener">View <span class="font-name"></span> font details</a> | |
<script> | |
<?php if(!$google_font) { ?> | |
jQuery('.font-details').hide(); | |
<?php } else { ?> | |
jQuery('.font-details').attr('href', 'https://fonts.google.com/specimen/<?php echo $google_font; ?>'); | |
jQuery('.font-name').text('<?php echo $google_font; ?>'); | |
<?php } ?> | |
jQuery('.font-selection').change(function(){ | |
if(jQuery(this).val() !='') { | |
var fontURL = 'https://fonts.google.com/specimen/'+jQuery(this).val(); | |
jQuery('.font-details').fadeIn(); | |
jQuery('.font-details').attr('href', fontURL); | |
jQuery('.font-name').text(jQuery(this).val()); | |
} else if(jQuery(this).val() =='') { | |
jQuery('.font-details').hide(); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment