wptt/webfont-loader

本地托管Web字体。

安装次数: 39,519

依赖项: 1

建议者: 0

安全性: 0

星标: 131

关注者: 17

分支: 12

类型:

v1.1.3 2022-10-21 07:56 UTC

This package is auto-updated.

Last update: 2024-09-22 14:04:38 UTC


README

下载Web字体(例如Google-Fonts),并在WordPress网站上本地托管。

这提高了性能(减少对多个顶级域的请求)并增加了隐私性。由于字体在本地托管在网站上,因此没有对第三方服务器的ping操作,因此没有跟踪。

用法

WordPress主题通常会使用wp_enqueue_style函数来排队资源

function my_theme_enqueue_assets() {
	// Load the theme stylesheet.
	wp_enqueue_style(
		'my-theme',
		get_stylesheet_directory_uri() . '/style.css',
		array(),
		'1.0'
	);
	// Load the webfont.
	wp_enqueue_style(
		'literata',
		'https://fonts.googleapis.com/css2?family=Literata&display=swap',
		array(),
		'1.0'
	);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_assets' );

为了本地托管Web字体,您首先需要从该存储库下载wptt-webfont-loader.php文件,并将其复制到您的主题中。一旦这样做,上述代码可以转换为以下内容

function my_theme_enqueue_assets() {
	// Include the file.
	require_once get_theme_file_path( 'inc/wptt-webfont-loader.php' );
	// Load the theme stylesheet.
	wp_enqueue_style(
		'my-theme',
		get_stylesheet_directory_uri() . '/style.css',
		array(),
		'1.0'
	);
	// Load the webfont.
	wp_enqueue_style(
		'literata',
		wptt_get_webfont_url( 'https://fonts.googleapis.com/css2?family=Literata&display=swap' ),
		array(),
		'1.0'
	);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_assets' );

可用函数

wptt_get_webfont_styles

$remote_url = 'https://fonts.googleapis.com/css2?family=Literata&display=swap';
$contents   = wptt_get_webfont_styles( $remote_url );

返回样式表内容,使用本地托管的Web字体。

wptt_get_webfont_url

$remote_url = 'https://fonts.googleapis.com/css2?family=Literata&display=swap';
$contents   = wptt_get_webfont_url( $remote_url );

返回样式表URL,本地托管。

为多个字体构建URL

$font_families = array(
	'Quicksand:wght@300;400;500;600;700',
	'Work+Sans:wght@300;400;500;600;700'
);

$fonts_url = add_query_arg( array(
	'family' => implode( '&family=', $font_families ),
	'display' => 'swap',
), 'https://fonts.googleapis.com/css2' );

$contents = wptt_get_webfont_url( esc_url_raw( $fonts_url ) );

支持IE

默认情况下,wptt_get_webfont_url将下载.woff2文件。但是,如果您需要支持IE,则需要使用.woff文件。要做到这一点,您可以在wptt_get_webfont_url函数中将woff作为第二个参数传递

wptt_get_webfont_url( 'https://fonts.googleapis.com/css2?family=Literata&display=swap', 'woff' );

存储在自定义目录中

如果您需要将字体文件存储在自定义目录中,您可以使用过滤器传递自定义路径和URL。确保您在调用包含WPTT_WebFont_Loader类的文件之前添加这些过滤器。

/**
 * Change the base path.
 * This is by default WP_CONTENT_DIR.
 *
 * NOTE: Do not include trailing slash.
 */
add_filter( 'wptt_get_local_fonts_base_path', function( $path ) {
	return WP_CONTENT_DIR;
} );

/**
 * Change the base URL.
 * This is by default the content_url().
 *
 * NOTE: Do not include trailing slash.
 */
add_filter( 'wptt_get_local_fonts_base_url', function( $url ) {
	return content_url();
} );

/**
 * Change the subfolder name.
 * This is by default "fonts".
 *
 * Return empty string or false to not use a subfolder.
 */
add_filter( 'wptt_get_local_fonts_subfolder_name', function( $subfolder_name ) {
	return 'fonts';
} );