WordPress.org

Forums

[resolved] Using a global variable (5 posts)

  1. goldenhills
    Member
    Posted 1 year ago #

    I want to add a gloabal variable once and then reference it on many pages. The value will change once a year so I would like to only have to update one file for it to automatically update all the pages.

    I am new at this. Can someone tell me if this will work or if there is an easier or better way?

    In my page.php file add:
    <?php global $CurrentYear = 'dog'; ?>

    Then on any page I can add:
    <?php echo 'This is the year of the ' . $CurrentYear; ?>

    Thank you!

  2. jmyeom
    Member
    Posted 1 year ago #

    you need to include the file with the variable into the file you want to call that variable from.... i.e

    page.php

    <?php
    $CurrentYear = 'dog';
    ?>

    any page

    <?php
    include 'page.php';
    echo $CurrentYear;
    ?>

    if you are trying to call the variable from within a function, you need to call it globally

    <?php
    include 'page.php';
    function year(){
        global $CurrentYear;
        echo $CurrentYear;
    }
    echo year();
    ?>
  3. goldenhills
    Member
    Posted 1 year ago #

    Oh. Somehow that seems inefficient. Is there no other way to do this that would be better? Maybe a define or something?

    Thanks for your reply!

  4. jmyeom
    Member
    Posted 1 year ago #

    you can define it, but it would still need to be included,

    you could always put the variable into the config file, as the config file is called with almost every page

    add it into the config, then you should be able to call it
    if set as a variable, then you will need to use global if inside a function,
    or you can define it, thus no global needed,

    define('CURRENT_YEAR', 'dog');

    echo CURRENT_YEAR;

  5. goldenhills
    Member
    Posted 1 year ago #

    That sounds like just what I am looking for. Thank you very much!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.