Home › Forums › General Issues › Showing post object field values within a wp_user_query loop › Reply To: Showing post object field values within a wp_user_query loop
Hi @rowanpurdy
You have two issues:
1. You’ve done a foreach loop of the post data and you even use wp_reset_postdata()
but you’ve missed the setup_postdata()
function.
2. Any function (ACF or WP Core) that is the_something()
echoes the results. This is not desired whenever you save the value to a variable.
Here’s your code (from the first snippet) modified:
<?php
$args = array(
'posts_per_page' => -1,
'cat' => $queryinfo->term_id
);
$user_query = new WP_User_Query( $args );
$users = $user_query->get_results();
if (!empty($users)) {
$people .= '<ul>';
foreach ($users as $user) { // loop through each user
$user_info = get_userdata($user->ID); // get all the user's data
$people .= '<li><a href="#"><span class="title">' . $user_info->first_name . ' ' . $user_info->last_name . '</span></a>';
if( !empty($user_info->description) ) {
$people .= '<span>' . $user_info->description . '</span>';
}
if( get_field('user_jobtitle', 'user_' .$user_info->ID) ) {
$people .= '<span>' . get_field('user_jobtitle', 'user_' .$user_info->ID) . '</span>';
}
$posts = get_field('user_organisation', 'user_' .$user_info->ID);
// Note that field 'user_organisation' is connected to the post object 'organisation' which is a custom post type
if( $posts ) {
foreach( $posts as $post) { // variable must be called $post (IMPORTANT)
setup_postdata($post);
$people .= get_the_title();
$people .= get_permalink();
}
wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
}
$people .= '</li>';
} // end for each loop
$people .= '</ul>';
} // end initial if statement
else{
$people .= 'Sorry, we don\'t currently have any people in this category.
';
}
echo $people;
?>
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
Accordions are a great way to group related information while allowing users to interactively show and hide content. In this video, Damon Cook goes in-depth on how to create an accessible accordion block using ACF PRO’s Repeater field.https://t.co/RXT0g25akN
— Advanced Custom Fields (@wp_acf) March 2, 2023
© 2023 Advanced Custom Fields.
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.