wp_add_inline_style() 中的未定义变量

Undefined variable in wp_add_inline_style()

我将网站更新为 PHP8 并在最后一行收到警告“未定义的变量 $customVariables” wp_add_inline_style( 'theme-style', $customVariables ); 代码如下:

function spectra_custom_styles($custom) {
    //Fonts
    $headings_font = esc_html(get_theme_mod('spectra_headings_fonts'));
    $body_font = esc_html(get_theme_mod('spectra_body_fonts'));
    if ( $headings_font or $body_font) {
        $customVariables = ":root{"."\n";
        if ( $headings_font ) {
            $font_pieces = explode(":", $headings_font);
            $customVariables .= "--c7-heading-font-family: {$font_pieces[0]};"."\n";
        }
        if ( $body_font ) {
            $font_pieces = explode(":", $body_font);
            $customVariables .= "--c7-font-family: {$font_pieces[0]};"."\n";
        }
        
        $customVariables .= "}";
        
    }

    //Output all the styles
        wp_add_inline_style( 'theme-style', $customVariables );
}

这是因为您只在 if 块中定义了 $customVariables。在 $headings_font or $body_font 计算结果为 false 的情况下,变量将为 Undefined.

你可以更新到这个:

function spectra_custom_styles($custom) {
    //Fonts
    $headings_font = esc_html(get_theme_mod('spectra_headings_fonts'));
    $body_font = esc_html(get_theme_mod('spectra_body_fonts'));
    $customVariables = "";

    if ( $headings_font or $body_font) {
        $customVariables .= ":root{"."\n";
        if ( $headings_font ) {
            $font_pieces = explode(":", $headings_font);
            $customVariables .= "--c7-heading-font-family: {$font_pieces[0]};"."\n";
        }
        if ( $body_font ) {
            $font_pieces = explode(":", $body_font);
            $customVariables .= "--c7-font-family: {$font_pieces[0]};"."\n";
        }
        
        $customVariables .= "}";
        
    }

    //Output all the styles
        wp_add_inline_style( 'theme-style', $customVariables );
}

或者您可以将 wp_add_inline_style 移动到 if 块内:

function spectra_custom_styles($custom) {
    //Fonts
    $headings_font = esc_html(get_theme_mod('spectra_headings_fonts'));
    $body_font = esc_html(get_theme_mod('spectra_body_fonts'));


    if ( $headings_font or $body_font) {
        $customVariables = ":root{"."\n";
        if ( $headings_font ) {
            $font_pieces = explode(":", $headings_font);
            $customVariables .= "--c7-heading-font-family: {$font_pieces[0]};"."\n";
        }
        if ( $body_font ) {
            $font_pieces = explode(":", $body_font);
            $customVariables .= "--c7-font-family: {$font_pieces[0]};"."\n";
        }
        
        $customVariables .= "}";


    //Output all the styles
        wp_add_inline_style( 'theme-style', $customVariables );
        
    }

}