Kirki框架自定义上传字体显示但不生效,如何输出@font-face代码?
解决Kirki框架自定义上传字体不生效的问题
问题背景
基于Kirki框架搭建了支持上传.woff格式字体的后台面板,字体文件上传成功后,自定义器中能看到上传的字体名称,但字体无法实际生效,怀疑问题出在mytheme_add_custom_fonts()函数的实现上。
现有代码
custom-fonts.php 原代码
function mytheme_add_custom_fonts() { $font_1 = mytheme_get_option( 'my_custom_font1' ); $fontfamily1 = mytheme_get_option( 'my_custom_fontfamily1' ); $output = ''; if ( $font_1 && $fontfamily1 ) { $output .= sprintf( ' @font-face {font-family: "%s";font-display: swap;src: local("%s"), url("%s") format("woff");}', esc_attr( $fontfamily1 ), esc_attr( $fontfamily1 ), esc_attr( $font_1 ) ); } echo $output; }
functions.php 原代码
function mytheme_get_custom_fonts($standard_fonts) { $fontfamily1 = mytheme_get_option( 'my_custom_fontfamily1' ); $list_fonts = array(); $list_fonts['Canela'] = array( 'label' => 'Canela', 'variants' => array( 'regular', '300italic' ), 'stack' => 'Canela', ); if ( $fontfamily1 ) { $list_fonts[ $fontfamily1 ] = $fontfamily1; } return array_merge_recursive( $list_fonts, $standard_fonts ); } add_filter( 'kirki/fonts/standard_fonts', 'mytheme_get_custom_fonts', 20 );
问题分析
- 字体输出逻辑错误:
mytheme_add_custom_fonts()直接使用echo输出CSS代码,没有通过WordPress的样式挂载钩子,导致代码无法被正确加载到前端页面。 - Kirki字体配置结构错误:动态添加上传字体时,仅传入了字体名称字符串,而非Kirki要求的包含
label、variants、stack的数组,导致字体无法被框架正确识别。
修复方案
1. 修正字体CSS输出逻辑
修改custom-fonts.php,使用WordPress官方方法将@font-face代码注入到页面样式中:
function mytheme_add_custom_fonts() { $font_1 = mytheme_get_option( 'my_custom_font1' ); $fontfamily1 = mytheme_get_option( 'my_custom_fontfamily1' ); $output = ''; if ( $font_1 && $fontfamily1 ) { $output .= sprintf('@font-face { font-family: "%s"; font-display: swap; src: local("%s"), url("%s") format("woff"); }', esc_attr( $fontfamily1 ), esc_attr( $fontfamily1 ), esc_attr( $font_1 ) ); } // 将自定义字体CSS追加到主题样式或默认块样式中 if ( ! empty( $output ) ) { // 替换成你的主题样式句柄,比如 'mytheme-style',没有的话用 'wp-block-library' wp_add_inline_style( 'wp-block-library', $output ); } } // 通过wp_enqueue_scripts钩子挂载函数,确保在样式加载时执行 add_action( 'wp_enqueue_scripts', 'mytheme_add_custom_fonts' );
2. 修正Kirki自定义字体数组结构
修改functions.php中的字体添加逻辑,确保数组格式符合Kirki要求:
function mytheme_get_custom_fonts($standard_fonts) { $fontfamily1 = mytheme_get_option( 'my_custom_fontfamily1' ); $list_fonts = array(); // 默认字体Canela的配置保持不变 $list_fonts['Canela'] = array( 'label' => 'Canela', 'variants' => array( 'regular', '300italic' ), 'stack' => 'Canela, serif', ); // 动态添加上传的字体,使用正确的数组结构 if ( $fontfamily1 ) { $list_fonts[ $fontfamily1 ] = array( 'label' => $fontfamily1, 'variants' => array( 'regular' ), // 根据上传字体的实际变体调整,比如有粗体则添加'700' 'stack' => $fontfamily1, serif, ); } // 使用array_merge而非array_merge_recursive,避免字体配置被意外合并 return array_merge( $list_fonts, $standard_fonts ); } add_filter( 'kirki/fonts/standard_fonts', 'mytheme_get_custom_fonts', 20 );
额外检查项
- 确认
mytheme_get_option函数能正确读取自定义器中保存的字体URL和家族名称。 - 打开浏览器开发者工具的Network面板,检查字体文件是否被成功请求(HTTP状态码为200)。
- 验证前端元素的CSS是否正确应用了该字体,例如:
font-family: "你的字体名称", sans-serif;。
内容的提问来源于stack exchange,提问作者justtme
相关产品推荐
相关产品推荐

