我将网站更新到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 );
}
}