WordPress中ACF自定义字段上传字体失效问题排查
问题排查与修复方案
核心错误点及修复方法
错误1:误用
the_sub_field()赋值变量the_sub_field()是直接输出字段内容的函数,无法将值返回给变量,会导致$upload_file和$title_name为空,同时字段值会被错误地提前输出到页面,最终@font-face中的字体名称和路径完全无效。
修复:替换为get_sub_field(),该函数返回字段值,适合赋值给变量。错误2:未遍历ACF重复字段组
从代码逻辑看,font_title是包含子字段的重复字段组类型,但当前代码没有通过have_rows()循环遍历字段组,直接调用子字段函数无法正确获取值。
修复:添加have_rows()循环,确保在循环内调用子字段。错误3:文件上传字段取值逻辑缺失
若ACF的upload_file字段设置为返回「文件对象」而非直接返回URL,直接使用get_sub_field('upload_file')得到的是数组,必须提取url属性才能拿到正确的字体文件路径。额外优化:字体格式兼容性
仅指定opentype格式无法覆盖所有浏览器,需根据上传字体的后缀匹配对应格式(如.ttf对应truetype,.woff2对应woff2)。
修正后的完整代码
<?php function so_extend_frequent_bought_shortcode2() { global $product; // 避免产品对象不存在时报错 if ( ! $product ) return; $id = $product->get_id(); $img = get_post_meta($id, 'wp_custom_attachment', true); $text = get_post_meta($id, 'text_input', true); $texz = !empty($text) ? $text : 'Text coming from Static resource'; // 开启输出缓冲,符合WordPress短代码规范 ob_start(); // 遍历重复字段组(单组数据也需循环一次) if ( have_rows('font_title') ) { while ( have_rows('font_title') ) { the_row(); $upload_file = get_sub_field('upload_file'); $title_name = get_sub_field('title_name'); // 处理文件对象/URL两种返回格式 $font_url = is_array($upload_file) ? $upload_file['url'] : $upload_file; // 自动匹配字体格式 $font_ext = pathinfo($font_url, PATHINFO_EXTENSION); $font_format = match($font_ext) { 'ttf' => 'truetype', 'otf' => 'opentype', 'woff' => 'woff', 'woff2' => 'woff2', default => 'opentype' }; ?> <style type="text/css"> @font-face { font-family: "<?php echo esc_attr($title_name); ?>"; src: url('<?php echo esc_url($font_url); ?>') format("<?php echo $font_format; ?>"); font-display: swap; /* 优化字体加载体验 */ } </style> <input type="text" class="font-input" id="font-input-<?php echo esc_attr($title_name);?>" value="<?php echo esc_attr($product->get_title());?>" style="font-family: '<?php echo esc_attr($title_name); ?>'; font-size: 120px;"> <?php } } return ob_get_clean(); } add_shortcode( 'my_new_shortcode2', 'so_extend_frequent_bought_shortcode2' );
额外说明
- 使用
ob_start()和ob_get_clean()包裹输出,避免短代码直接输出导致的页面内容顺序混乱,符合WordPress短代码开发规范。 - 添加
esc_attr()、esc_url()转义处理,防止XSS安全漏洞。 - 新增
font-display: swap,确保字体加载期间页面文本不会空白,提升用户体验。
内容的提问来源于stack exchange,提问作者etrafart
相关产品推荐
相关产品推荐

