• Resolved kasperbs

    (@kasperbs)


    Hi I would like to set a variable that i can use on all my template pages without having to set it everytime. I would for example like this to be available in all template files:
    $image_path = '/wp-content/uploads/images/';
    How would I go about doing that so that I didn’t have to specify that line in all the template files?

    thanks

Viewing 6 replies - 1 through 6 (of 6 total)
  • Probably the easiest would be to put it in the header.php file since it’s loaded for every page wp generates.

    Moderator Samuel Wood (Otto)

    (@otto42)

    www.remarpro.com Admin

    The header.php won’t work unless you declare it global, as header.php is called inside a function scope.

    If it’s theme specific, then the theme’s functions.php is the best place for it. Make sure to specify it to be global. Also make sure to make it a theme specific name so that it doesn’t conflict with anything. Like so:

    <?php
    // whatever else is in functions.php
    
    global $themename_image_path;
    $themename_image_path = 'whatever';
    ?>

    In header.php and footer.php and sidebar.php you’ll probably need to also specify that the variable is global in order to be able to use it there as well. This is because these files are included via function calls instead of normal includes. This is intentional, so try not to bypass it by including files directly in your theme.

    If you don’t like having to have it global all the time, then a better way than using a variable is to use a function. Like this:

    <?php
    // whatever else is in functions.php
    
    function get_themename_image_path() {
    return 'whatever';
    }
    ?>

    Then you just use get_themename_image_path() whenever you need the image path.

    Thread Starter kasperbs

    (@kasperbs)

    Thanks but it doesn’t work. I put this in the header:
    <?php $image_path = '/wp-content/uploads/images/reviews/'; ?>

    Then echo $image_path in home.php but it didn’t work. It only worked if I put that variable in the home.php file

    Moderator Samuel Wood (Otto)

    (@otto42)

    www.remarpro.com Admin

    kasperbs: Looks like we cross-posted. Read my reply above, it has the answer you need.

    Go with otto’s advice

    Thread Starter kasperbs

    (@kasperbs)

    Thanks Otto42, that works. Thanks for the explanation as well. it’s always nice to know what you are doing.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Set a Varible to use on all template files’ is closed to new replies.