How to Use Global Variables Inside Header and Footer

I set global variables for some custom user data in my functions.php to use them in navigation inside header and footer.

if (is_user_logged_in()) {
    # users wordpress id
    global $user_id_wp;
    $user_id_wp = get_current_user_id();
    # users meta page id
    global $user_id_meta;
    $user_id_meta = userMeta(get_current_user_id());
    # users uuid
    global $user_id_uuid;
    $user_id_uuid = get_field(user-uuid, $user_id_meta);
}

Those variables cannot be used inside header.php and footer.php where I need them. Cannot be used means var_dump($user_id_meta) results in NULL, while userMeta($user_id_wp) shows the correct values inside header or footer.

I have tried to set the lines above as function with add_action( 'init', 'globalUserVar' ); but no positive results either. Please help me use my global user vars inside the header and footer. Thanks so much!

Topic globals functions users Wordpress

Category Web


In functions.php you can create a constant with the user id, like this.

// if somehow this constant exists this will prevent a php error
if (!defined('CURRENT_USER_ID')) {
    // if user is not logged it this constant will contain 0
    define('CURRENT_USER_ID', get_current_user_id());
}

Now you have a constant variable available anywhere in your theme.

To access it you can simply call it, for example

echo CURRENT_USER_ID;

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.