0

I am creating a custom theme based on _S blank theme. I created a php file named aa-config.php with set of variables, then <?php require get_template_directory() . '/inc/aa-config.php'; ?> this to add those variables in WordPress. Then, I tried to add a variables in footer.php using <?php echo $fburl; ?> but nothing is showing. aa-config.php:

<?php
$fburl = 'vvv';
?>

I read an answer but it doesn't help me because I will add more than one dozon of variables in that aa-config.php.

  • Variables defined like this will have global scope. You should use global for accessing. global $my_variable; echo $my_variable;. – Nilambar Jul 2 '15 at 10:50
  • Where I use global $my_variable? Can I do it in aa-config.php? Can I shortly do this in any short way in all variables of aa-config.php? or I have to add it every place I want to echo $my_variable? p.s: I am not good at php. – Sahriar Saikat Jul 2 '15 at 10:56
0

There are several ways you could do this. As noted above, you can call global every time you want the value:

global $fburl;
echo $fburl;

You can put all your config settings into a single object or array, then put that one object into the globals so it's available everywhere (doable, but not one I'd choose).

One popular method is to wrap your config settings in a class, then use a getter when you need the value. This assumes that the configuration gets set one time and doesn't need to be modified on the fly. Here I'm specifically not using the __get() magic method, but creating my own as an example of how it works.

class My_Config {
    private static $config_vars = [
        'fburl' => 'vvv',
    ];

    public static function get_config( $var_name ) {
        if ( array_key_exists( $var_name, self::$config_vars ) ) {
            return self::$config_vars[ $var_name ];
        }

        return null;
    }
}

Now any time you need the value of a defined setting, you'd use (with proper escaping, of course):

echo My_Config::get_config( 'fburl' );
  • THanks. Calling global in everywhere is distrubing and messy. I better do it with class. – Sahriar Saikat Jul 5 '15 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.