Support

Account

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;
    ?>