Skip to content
JIX edited this page Jul 14, 2020 · 1 revision

Purpose

The Font field loads and displays fonts from the Google Font Library and allows users to preview and select them.

Play Preview Video

Settings

Font fields do not have any field-based settings, however you must enter an API key for Google Fonts in the settings page of the plugin.

If you have not disabled the administration interface, please go to Ultimate Fields > Settings and enter an API key in the "Google Fonts API Key" field. There are instructions on where to do it on the page.

If you are using PHP you have two options:

  1. Use the set_api_key method of the field.
  2. Use the uf.field.font.api_key filter.
// Use a global filter
add_filter( 'uf.field.font.api_key', 'my_api_key' );
function my_api_key() {
	return 'AIzaSyCmiGD2rK9-e_-excC1iv6h9Q6iIs1ftn4';
}

// Use the method
$fields = array(
	Field::create( 'font', 'body_font' )
		->set_api_key( 'AIzaSyCmiGD2rK9-e_-excC1iv6h9Q6iIs1ftn4' )
);

In order to avoid the accidental distribution of your private API keys, please avoid saving them in your theme/plugin. It is a much better idea to define a constant in wp-config.php and use it in the theme/plugin.

Usage

Using get_value for a font field will return an array, which contains:

  • family, which is the selected font-family.
  • variants, which contains all selected variants.

You can then use the Ultimate_Fields\Field\Font::get_font_url() method to generate a stylesheet URI based on the selection and add it as a WordPress style.

Then you can use the family in order to enable the font for a selected area. Please note that it is not recommended to use a single font-weight for a specific element, as this will easily lead to over-usage of fonts.

add_action( 'wp_enqueue_scripts', 'theme_custom_font' );
function theme_custom_font() {
	$font = get_value( 'font_field', 'option' );

	if( ! $font ) {
		return;
	}

	// Enqueue the actual font
	$url = UF\Field\Font::get_font_url( $font );
	wp_enqueue_style( $font['family'], $url );

	// Add some styles
	$css = 'body {
		font-family: "' . $font['family'] . '", Sans-Serif;
	}';
	wp_add_inline_style( $font['family'], $css );
};
Clone this wiki locally