value only displaying from echo

This is probably a really simple question and Im sorry if it is. However I have been searching and cannot see a solution.

I am using wordpress as a CMS and am enqueue google fonts based on a variable as so

Read More
if (!function_exists('opd_load_google_style'))  {
    /* Add Google Fonts */
    global $opd_albaband;
    $google_font = $opd_albaband['typography_h1']['font-family'];

    function opd_load_google_style() {
        if (!is_admin()) {
            wp_register_style('googleFont','http://fonts.googleapis.com/css?family='.$google_font.' 400,700');
            wp_enqueue_style('ggl', get_stylesheet_uri(), array('googleFont') );
        }
    }
    add_action('wp_enqueue_scripts', 'opd_load_google_style');
}

However this produces a Undefined variable $google_font. I can get $google_font to display using echo $google_font but this would not work with wp_register_style

Am I missing something? Sorry for its simplicity.

Related posts

Leave a Reply

2 comments

  1. Your $google_font variable is out of scope so you can’t useit in your opd_load_google_style function. Instead your code should look like this

    if (!function_exists('opd_load_google_style'))  {
    
        function opd_load_google_style() {
    
            /* Add Google Fonts */
            global $opd_albaband;
            $google_font = $opd_albaband['typography_h1']['font-family'];
    
            if (!is_admin()) {
                wp_register_style('googleFont','http://fonts.googleapis.com/css?family='.$google_font.' 400,700');
                wp_enqueue_style('ggl', get_stylesheet_uri(), array('googleFont') );
            }
        }
        add_action('wp_enqueue_scripts', 'opd_load_google_style');
    }
    

    Or you could pass the $google_font variable to your function by doing

    function opd_load_google_style($google_font) {
        //Inside your function you now have access to $google_font
    }
    
  2. You just need to shuffle things around a bit, as your opd_load_google_style function does not have access to $google_font.

    if (!function_exists('opd_load_google_style'))  {
        function opd_load_google_style() {
            /* Add Google Fonts */
            global $opd_albaband;
    
            $google_font = $opd_albaband['typography_h1']['font-family'];
            if (!is_admin()) {
                wp_register_style('googleFont','http://fonts.googleapis.com/css?family='.$google_font.' 400,700');
                wp_enqueue_style('ggl', get_stylesheet_uri(), array('googleFont') );
            }
        }
    }