0

I've got a partial called within single.php that looks like this:

<?php   $userdata = get_userdata($post->post_author) ;  ?>  
<div class="entry-meta"> 
    <span class="byline author vcard"><?= __('By', 'sage'); ?>
    <a href="<?= get_author_posts_url(get_the_author_meta('ID')); ?>" rel="author" class="fn">
        <?php  echo ucfirst($userdata->user_nicename)  ?>
    </a>
    </span>    
</div>

Now, $userdata might be useful elsewhere within my single. So I'd like the variable and its value to be available globally within all templates that are included whenever my single is used.

So I cut out the first line: the creation of $userdata and put earlier in a 'parent' template that gets called earlier in the loop.

Alas, the variable was no longer avaiable to the partial. I tried a few other templates that are also called earlier in the loop. I got the same result: the variable wasn't available.

I thought about creating a function within functions.php. But I can think of a couple of reasons not to do this. First of all, why bother with an abstraction for get_userdata() when get_userdata already exists? This seems inelegant.

  • WP caches the user information. There's really no problem just to call get_userdata every time you need it. The only thing you are doing by transfering it to a variable $userdata is have WP fetch it from another place in the memory. – cjbj Sep 1 '16 at 8:09
  • @cjbj as an answer please :) – Rarst Sep 2 '16 at 17:23
  • @Rarst Yessir! Done sir! – cjbj Sep 3 '16 at 12:13
4

WordPress caches the user information. There's really no problem just to call get_userdata every time you need it. The only thing you are doing by transfering it to a variable $userdata is have WP fetch it from another place in the memory.

Note: read this post for a more general dealing with passing variables to partials.

0

There are two solutions:

1) Use a variable like this global $userdata;

$userdata = //object you want inside partial;

and then use

global $userdata; inside that single.php or loop etc.

Reference: https://developer.wordpress.org/reference/functions/get_template_part/

2) Keep doing the things as you are except one change instead of get_template_part use include_once('filename.php')

  • Both are ways to circumvent WP's preferred way of doing this. Possible, but not recommended. – cjbj Sep 1 '16 at 8:10
  • What is recommended then? Please share so we can learn something better. – WordPress Mechanic Sep 2 '16 at 14:46
  • See my comment under the question. There is no problem here. Also read this post – cjbj Sep 2 '16 at 14:58

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.