0

I'm using a template part to repeat the HTML for each result when performing a WP_User_Query to return a list of users. However I am finding that the Advanced Custom Fields data isn't returning.

// WP_User_Query arguments
$args = array(
    'role'      => 'advisor',
    'number'    => 6
);
// The User Query
$user_query = new WP_User_Query( $args );
if ( ! empty( $user_query->get_results() ) ) :
    foreach ( $user_query->get_results() as $user ) {
        get_template_part('template-parts/advisor');
    }
endif;

...and a simple example of the template part itself:

<?php
    $advisor_heading = get_field('advisor_heading', 'user_'.$user->ID);
?>

<div class="advisor__heading">
    <h2><?php echo $advisor_heading; ?></h2>
</div>

So the HTML is returning of course, but the ACF user data is not. It works fine if I don't use a template part and instead hard code it into the foreach loop, but in this case I need to use the template part.

Hope somebody can help!

2
  • this is highly unlikely to be related to ACF, and more that you're trying to use the $user variable from the loop in another file without passing it along, so it does not exist in the template part. This would be true even if the user query did not exist and you wrote $user = 'test'; get_template_part(..... Also 'orderby' => 'rand', is obscenely slow/expensive, you should avoid it at all costs, as well as that why use the old admin AJAX API to print out JSON when there's a modern dedicated REST API that natively speaks JSON
    – Tom J Nowell
    Commented Nov 13, 2023 at 15:34
  • @TomJNowell thanks. I'm not very familiar at all with Ajax to be honest, and so that's a cut-and-paste job I found somewhere which loads more results. Actually I've edited my question, as I don't even think Ajax is the issue here either. What you have said makes sense. So I need to pass the variable along somehow. Also only using 'rand' in my local build so I can see different results appear. The end product will not use this. Commented Nov 13, 2023 at 15:46

1 Answer 1

0

You need to pass the variables to the template using the 3rd parameter of get_template_part:

get_template_part( string $slug, string|null $name = null, array $args = array() ): void|false

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

For example: https://developer.wordpress.org/reference/functions/get_template_part/#comment-4130

Note: This was added in WordPress v5.5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.