Support

Account

Home Forums General Issues How to sort/order select values from ACF field Reply To: How to sort/order select values from ACF field

  • Ok I think I’ve solved the solution (thanks to James from support too), leaving the answer here for anyone else, I used the documentation here to support it and :

    Doc

    In the ACF back-end I changed the choices like this:

    January : January to 1 : January
    February: February to 2 : February

    Changing the key to a numeric value for sorting later. Now in the code I did this:

    <?php 
    	$args = array(
    		'post_type' => 'activities',
    		'posts_per_page'   => -1
    	);
    	$query = new WP_Query( $args );
    ?>
    
    <?php
    
    	$data;
    
    	// Create array of posts and fields
    	$myposts = get_posts( $args ); 
    	foreach ( $myposts as $key => $post ) : setup_postdata( $post );
    		
    		$data['locations'][] = get_field('location');
    		$data['activity'][] = get_field('activity_type');
    		$data['difficulty'][] = get_field('difficulty');
    		// To sort months by the key value (not the label) get the field object - choice
    		// then grab the values like above
    		$monthField = get_field_object('availability');
    		$monthValue = get_field('availability');
    
    		// Get months, iterate through the choices
    		foreach($monthField as $month) {
    			$monthField['choices'][$monthValue] = $month;
    			
    		}
    		
    	endforeach;
    
    	
    	// Omit duplicate results
    	foreach($data as $key => $value) {
    		$data[$key] = array_unique($data[$key]);
    	}
    	
    	// sorted by alphabet
    	natsort($data['locations']);
    	natsort($data['difficulty']);
    	natsort($data['activity']);
    	// sorted by the key
    	ksort($monthField['choices']);
    
    	wp_reset_postdata();
    ?>

    And the html:

    	<select name='month'>
    				<option value='' disabled selected>Choose Month</option>
    				<?php
    					foreach($monthField['choices'] as $month) {
    						echo "<option value='{$month}'>{$month}</option>";
    					}
    				?>
    			</select>

    Using the field object and using ksort solved the problem here, tested and seems to work well.