首页 > 解决方案 > WordPress - Google 字体在 .php 文件中不起作用

问题描述

我使用“WooCommerce PRO 的灵活发票”插件,但我遇到了问题。基于 .php 文件,生成一个 .pdf 文件。我在 .php 文件中添加了 Poppins 字体的链接,但是在网页上打开文件后,字体不起作用。最终,它应该是一个pdf文件。我尝试了不同的观点:

  1. 我添加到部分和容器中
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;600;700;900&display=swap" rel="stylesheet">
body, p, tr, th, td {font-family: 'Poppins', sans-serif!important;}
  1. 我使用了@import 选项:
@import 'https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;600;700;900&display=swap';
  1. 我使用了一个单独的 .css 文件和 @media print {}
  2. 我在functions.php文件中添加了一个函数
function wpb_add_google_fonts() {
   wp_enqueue_style( 'wpb-google-fonts', 'https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;600;700;900&display=swap', false );
   }
   
   add_action( 'wp_enqueue_scripts', 'wpb_add_google_fonts' );

不幸的是,Poppins 字体仍然不起作用。您对如何解决它有任何想法吗?

标签: javascriptphpjquerycsswordpress

解决方案


一切都在我的尽头。Poppins 正确渲染。这是我测试过的。

<?php

/**
 * Enqueue Poppins font from Google Fonts.
 *
 * @link https://fonts.google.com/specimen/Poppins?query=Poppins#about
 */
wp_enqueue_style( 'google_fonts', 'https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap', array(), wp_get_theme()->version, 'all' );

add_action( 'style_loader_tag', 'style_loader_tag_google_fonts', 10, 3 );
if ( ! function_exists( 'style_loader_tag_google_fonts' ) ) {
    function style_loader_tag_google_fonts( $tag, $handle, $src ) {
        if ( 'google_fonts' === $handle ) {
            $tag = str_replace(
                "<link rel='stylesheet'", 
                "<link rel='preconnect' href='" . esc_url( 'https://fonts.gstatic.com' ) . "' /><link rel='stylesheet'", 
                $tag
            );
        };
        return $tag;
    };
};

您也可以media="print"直接从标签中指定。

//... array(), wp_get_theme()->version, 'print' );

推荐阅读