0

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!

5
  • 1
    Is there a specific reason you don't simply call get_current_user_id() (as well as userMeta() and get_field()) in your header and footer templates?
    – Sally CJ
    Aug 18, 2021 at 8:32
  • 1
    Global variables are generally a bad idea. Rather than using them I'd suggest writing functions that return the values you want and using that. Aug 18, 2021 at 10:05
  • @JacobPeattie, that would have been my "workaround", but if you think it's the better solution, I prefer that for future needs. Aug 18, 2021 at 11:14
  • Thanks, @SallyCJ. I really don't need the $user_id_wp, but those other two are needed independently of each other through the theme, not only in header and footer. That's simply easier for me. Aug 18, 2021 at 11:16
  • @RobinAlexander What I was saying is, for example in footer.php, sidebar.php or a template part, why not just call userMeta(get_current_user_id()) or (by passing a specific user ID - userMeta( 123 )) right in that template file? And same goes with get_field().
    – Sally CJ
    Aug 18, 2021 at 13:05

1 Answer 1

1

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;
1
  • Never thought of constants! Great solution. Thank you very much for helping so fast! Aug 18, 2021 at 7:22

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .