Skip to content

Instantly share code, notes, and snippets.

@rodgerthat
Created November 17, 2021 18:41
Show Gist options
  • Save rodgerthat/99e0dd5f5a515edf1b1b4f4c9fcffc31 to your computer and use it in GitHub Desktop.
Save rodgerthat/99e0dd5f5a515edf1b1b4f4c9fcffc31 to your computer and use it in GitHub Desktop.
Font.php
<?php namespace FSM\Themes\Core\Customizer\Controls;
use Timber;
use WP_Customize_Control;
use FSM\Library\Exceptions\BadResponseException;
use FSM\Library\Exceptions\BadConfigException;
/**
* Customize Fonts Class
*
* @see WP_Customize_Control
*/
class Font extends WP_Customize_Control
{
/**
* @access public
* @var string
*/
public $type = 'font';
/**
* @access public
* @var array
*/
public $statuses;
/**
* Google fonts
* @var array
*/
public static $googleFonts = [];
/**
* Allowed font variants from Google fonts
* @var array
*/
public static $allowedVariants = [
'regular',
'italic',
'400',
'400italic',
'700',
'700italic'
];
/**
* Non-Google fonts
* @var array
*/
public static $nermalFonts = [
'arial' => [
'name' => 'Arial',
'css' => 'Arial,"Helvetica Neue",Helvetica,sans-serif',
'category' => 'sans-serif',
'url' => false
],
'helvetica' => [
'name' => 'Helvetica',
'css' => '"Helvetica Neue",Helvetica,Arial,sans-serif',
'category' => 'sans-serif',
'url' => false
],
'verdana' => [
'name' => 'Verdana',
'css' => 'Verdana,Geneva,sans-serif',
'category' => 'sans-serif',
'url' => false
],
'times' => [
'name' => 'Times New Roman',
'css' => 'TimesNewRoman,"Times New Roman",Times,Baskerville,Georgia,serif',
'category' => 'serif',
'url' => false
],
'georgia' => [
'name' => 'Georgia',
'css' => 'Georgia,Times,"Times New Roman",serif',
'category' => 'serif',
'url' => false
],
'tahoma' => [
'name' => 'Tahoma',
'css' => 'Tahoma,Verdana,Segoe,sans-serif',
'category' => 'sans-serif',
'url' => false
],
'courier-new' => [
'name' => 'Courier New',
'css' => '"Courier New",Courier,"Lucida Sans Typewriter","Lucida Typewriter",monospace',
'category' => 'monospace',
'url' => false
],
'trebuchet-ms' => [
'name' => 'Trebuchet MS',
'css' => '"Trebuchet MS","Lucida Grande","Lucida Sans Unicode","Lucida Sans",Tahoma,sans-serif',
'category' => 'sans-serif',
'url' => false
],
];
/**
* Constructor.
*
* @uses WP_Customize_Control::__construct()
*
* @param WP_Customize_Manager $manager Customizer bootstrap instance.
* @param string $id Control ID.
* @param array $args Optional. Arguments to override class property defaults.
*/
public function __construct($manager, $id, $args = array())
{
$this->statuses = array( '' => __('Default') );
if (empty(self::$googleFonts)) {
self::$googleFonts = self::retrieveFonts();
}
parent::__construct($manager, $id, $args);
}
/**
* Get Google Fonts (cached or from the remote API)
* @return array A list of available Google Fonts
*/
public static function retrieveFonts()
{
$googleFonts = get_option('fsm_google_fonts');
if (is_array($googleFonts)) {
return $googleFonts;
}
if (defined('FSM_GOOGLE_PUBLIC_API_KEY')) {
$response = wp_remote_get('https://www.googleapis.com/webfonts/v1/webfonts?&sort=popularity&key='.FSM_GOOGLE_PUBLIC_API_KEY);
if (!is_wp_error($response) && $response['response']['code'] < 400) {
$googleFontsRaw = json_decode(wp_remote_retrieve_body($response), true);
$googleFonts = self::prepGoogleFontsArray($googleFontsRaw['items']);
update_option('fsm_google_fonts', $googleFonts);
return $googleFonts;
} else if (is_wp_error($response)) {
throw new BadResponseException($response->get_error_message());
}
} else {
error_log('[ERROR retrieveFonts] Google API key not defined');
}
}
/**
* Prepare the Google fonts array for storage
*/
public static function prepGoogleFontsArray($googleFontsRaw)
{
$googleFonts = self::$nermalFonts;
foreach ($googleFontsRaw as $font) {
$googleFonts[sanitize_title($font['family'])] = [
'name' => $font['family'],
'css' => "\"{$font['family']}\",{$font['category']}",
'category' => $font['category'],
'url' => self::getGoogleFontUrl($font),
];
}
return $googleFonts;
}
/**
* Generate a Google fonts URL for the specified font
* @param array $font A Google font
* @return string The URL from which to load the google font
*/
private static function getGoogleFontUrl($font)
{
$fontUrl = []; // Initialize an empty array for constructing the URL to retrieve the font
$fontUrl[] = 'https://fonts.googleapis.com/css?family='; // Base request URL
$fontUrl[] = preg_replace('/ /', '+', $font['family']); // Font name (URL friendly)
// Figure out variants
$variantString = []; // Initialize an empty array for constructing the variants chunk of the URL
foreach (self::$allowedVariants as $variant) {
if (in_array($variant, $font['variants'])) {
if ($variant === 'regular') { // Change regular (in the JSON response) to 400 (for the font include URL)
$variant = '400';
}
if ($variant === 'italic') { // Change italic (in the JSON response) to 400italic (for the font include URL)
$variant = '400italic';
}
$variantString[] = $variant;
}
}
if (!empty($variantString)) {
$fontUrl[] = ':'.implode(',', array_unique($variantString));
}
$fontUrl = implode('', $fontUrl);
return $fontUrl;
}
/**
* Enqueue scripts/styles for the font picker.
*/
public function enqueue()
{
wp_enqueue_script('fsm-font-picker');
wp_enqueue_style('fsm-font-picker');
wp_localize_script('fsm-font-picker', 'fontQueryUrl', site_url('/admin-customizer/fonts'));
}
private static function getCategories($googleFonts)
{
return array_unique(array_map(function ($font) {
return $font['category'];
}, $googleFonts));
}
public function render_content()
{
$context = [
'label' => $this->label,
'description' => $this->description,
'fonts' => self::$googleFonts,
'link' => $this->get_link(),
'value' => $this->value(),
'id' => $this->id,
'fontCategories' => self::getCategories(self::$googleFonts),
];
Timber::render('admin/customizer/control/font.twig', $context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment