Support

Account

Home Forums General Issues Need to create a loop based on results from multi-select users Reply To: Need to create a loop based on results from multi-select users

  • Hi @lewmaster

    So if I’ve understood your issue correctly you’re trying to have a loop of posts which will only contain items where the ID of the logged in user matches the 1 or more users selected within the custom field you have setup? If that’s correct the code below should get you going in the right direction. Have commented inline and done some basic testing though you’ll need to adapt it to your needs. Hope it helps!

    <?php 
    //first let's check to makes sure the user is logged in
    if ( is_user_logged_in() ) : 
    
    //We set up our $user_ID global variable
    global $user_ID; 
    //populate above global
    get_currentuserinfo(); 
    
    //Create a set of arguments for our query
    $args = array(
    	'post_type'=> 'post',
    	'meta_query' => array(
    		array(
    			'key' => 'product_vendor_name', // name of custom field
    			'value' => serialize(strval($user_ID)), // matches post ID exactly e.g. "123", not just 123. This prevents a match for "1234"
    			'compare' => 'LIKE'
    		)
    	)
    );
    
    //Then run our query
    $myposts = new WP_Query($args);
    
    if ($myposts->have_posts()) : while ($myposts->have_posts()) : $myposts->the_post(); ?>
    
    <!-- Do your stuff here for the display of each post-->
    
    <?php 
    endwhile; //end our loop
    
    else: ?>
    
    	<p>no matching posts</p>
    
    <?php endif;
    
    // IMPORTANT - reset the $post object so the rest of the page works correctly
    wp_reset_postdata();  ?>
    								
    
    <?php 
    // If the user is not logged in provide an alternative display or message
    else :  ?>
    
    	<p>Not logged in message</p>
    	
    <?php endif; ?>