Support

Account

Home Forums General Issues Checking current logged in user against acf user multiselect field Reply To: Checking current logged in user against acf user multiselect field

  • Hey @walkers_inspiration

    Just a minor tweak to @imaginedd solution. You need to do a proper wrap of the if statement since you both assign a value and break the foreach loop. Otherwise the foreach will always break on first iteration.

    
    <div class="module_col">
    
    	<h3><?php the_sub_field('module_title'); ?></h3>
    
    	<?php
    	// Get List of students to check for eligibility
    	$students_list = get_sub_field('student_availability' );
    
    	// Set the default state to false, to be changed later
    	$student_authorised = false;
    
    	// Loop through students_list to check if user is allowed access
    	foreach( $students_list as $student ) :
    
    		// If user is in the list, set student_authorised to true and break out of loop
    		//(no need to loop through everybody if they're the first user)
    		if( in_array( $student_username, $student['nickname'] ) ){
    			$student_authorised = true;
    			break;
    		}
    
    	endforeach;
    
    	// If student is in the list, show download link
    	if ( $student_authorised ) : ?>
    	
    
    		<a href="<?php the_sub_field('module_download'); ?>">
    			<button class="download_btn">
    				<span><i class="fa fa-cloud-download"></i>Download Module</span>
    			</button>
    		</a>
    	
    
    	<?php 
    	// if student not in list, show authentication error
    	else : echo 'Not logged in'; endif; ?>
    
    </div>
    

    A different solution would be to fetch the ID of the current user instead and fetch the acf value unformatted. This is a bit more straight forward 🙂

    
    <?php $current_user_id = get_current_user_id(); ?>
    <?php if( have_rows('course_modules') ): ?>
    	<?php while ( have_rows('course_modules') ) : the_row(); ?>
    		<div class="module_container">
    			<div class="module_col">
    				<h3><?php the_sub_field('module_title'); ?></h3>
    				<?php $allowed_user_ids = get_sub_field('student_availability', false ); ?>
    				<?php if ( in_array( $current_user_id, $allowed_user_ids ) ): ?>
    					<a href="<?php the_sub_field('module_download'); ?>">
    						<button class="download_btn"><span><i class="fa fa-cloud-download"></i>Download Module</span></button>
    					</a>
    				<?php else : ?>
    					<p><?php _e('You\'re not allowed to download this module'); ?></p>
    				<?php endif; ?>
    			</div>
    			<div class="module_col">
    				<?php the_sub_field('module_details'); ?>
    			</div>
    		</div>
    	<?php endwhile; ?>
    <?php endif; ?>