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


Need to create a loop based on results from multi-select users

  • Hi, I set up a multi-select users field to attach multiple users to a post. I have used the following code to determine that the values are being correctly pulled:

    $values = get_field('product_vendor_name');
    echo '<ul>'; 
    foreach($values as $value)
    echo '<li>' . $value['user_nicename'] . '</li>';
    echo '</ul>';

    What I want to do now is create a loop based on the data returned above to display posts where the current logged in user matches one of the user values I have assigned to a post with the custom field.

    I am getting so close… If anyone can help me with this I would be infinitely grateful!

    Thanks in advance!

  • 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!

    //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
    //Create a set of arguments for our query
    $args = array(
    	'post_type'=> 'post',
    	'meta_query' => 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-->
    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();  ?>
    // If the user is not logged in provide an alternative display or message
    else :  ?>
    	<p>Not logged in message</p>
    <?php endif; ?>
  • That worked flawlessly, thank you SO much!!

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Need to create a loop based on results from multi-select users’ is closed to new replies.