我正在Customizer中创建一个Google字体控件。我创建了一个具有两个设置的自定义控件-一个用于字体系列,另一个用于字体权重。将分别为这两个项目选择dropwdowns。现在我想要的是,每当我更改字体系列时,字体权重都会自动填充该系列的相应权重。
我使用Google fonts API获取字体数据,该API由所有字体的对象数组组成。我还创建了一个包含所有字体的下拉列表。
以下是自定义控件的完整代码-
class itng_Google_Font_Dropdown_Custom_Control extends WP_Customize_Control {
private $fonts = false;
private $fontValue = \'\';
private $weightValue = \'\';
public function __construct( $manager, $id, $args = array(), $options = array() )
{
$this->fonts = $this->get_fonts();
parent::__construct( $manager, $id, $args );
}
public function render_content() {
if ( !empty( $this->fonts ) ) {
$this->render_fonts();
$this->render_weights();
}
}
/**
* Render the content of the category dropdown
*
* @return HTML
*/
protected function render_fonts() {
?>
<label>
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<select <?php $this->link(\'font\'); ?>>
<?php
foreach ( $this->fonts as $k => $v ) {
printf(\'<option value="%2$s" %1$s>%2$s</option>\', selected($this->value(\'font\'), $v->family, false), $v->family);
}
?>
</select>
</label>
<?php
}
protected function render_weights() {
?>
<h4>Weights</h4>
<?php
$font_weights = [\'100\', \'200\', \'300\', \'400\', \'500\', \'600\', \'700\', \'800\', \'900\'];
//var_dump( $this->fonts );
foreach( $this->fonts as $font ) {
if ( $font->family = $this->value(\'font\') ) {
$variants = $font->family;
}
}
var_dump( $variants );
}
/**
* Get the google fonts from the API or in the cache
*
* @param integer $amount
*
* @return String
*/
public function get_fonts( $amount = 100 ) {
$fontFile = get_template_directory() . \'/assets/fonts/cache/google-web-fonts.txt\';
//Total time the file will be cached in seconds, set to a week
$cachetime = 86400 * 7;
if(file_exists($fontFile) && $cachetime < filemtime($fontFile ) )
{
$content = json_decode(file_get_contents($fontFile));
} else {
$googleApi = \'https://www.googleapis.com/webfonts/v1/webfonts?sort=popularity&key=AIzaSyA9-9K8wV9KWKWY84Sp5TLSS7p9GguLRh4\';
$fontContent = wp_remote_get( $googleApi, array(\'sslverify\' => false) );
$fp = fopen($fontFile, \'w\');
fwrite($fp, $fontContent[\'body\']);
fclose($fp);
$content = json_decode($fontContent[\'body\']);
}
if($amount == \'all\')
{
return $content->items;
} else {
return array_slice($content->items, 0, $amount);
}
}
}
现在我想知道在
render_weights
方法获取中选定字体的权重
render_font
方法