Undefined variable in wp_add_inline_style()

278 views Asked by At

I updated the website to PHP8 and getting the Warning "Undefined variable $customVariables" on the last line with wp_add_inline_style( 'theme-style', $customVariables ); The code is below:

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 );
}
1

There are 1 answers

0
mikerojas On BEST ANSWER

this is because you only define $customVariables inside your if block. In the case $headings_font or $body_font evaluates to false the variable will be Undefined.

You can update to this:

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 );
}

or you can move wp_add_inline_style to inside the if block:

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 );
        
    }

}