Support

Account

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

Solved

How to sort/order select values from ACF field

  • I’ve taken over a project and I’m a bit stuck with some code left by a previous developer. Currently he’s using ACF to populate the fields of a search form. It all works as it should and I don’t want to change the code too much. Here’s what it currently looks like:

    acf custom search form

    These fields originate from the ACF fields plugin, he’s set checkbox and select fields in a custom post like this:

    acf back end

    However as you can see in the first picture the months are being populated in the wrong order (I guess by post date?) not in the original ACF order. My question is how can I modify his existing code to sort months correctly and other fields such as grade -(easy>medium>hard). Here’s the code that I’m working with:

    <?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');
    
        // Get months
        foreach(get_field('availability') as $month) {
            $data['months'][] = $month;
        }
    
    endforeach;
    
    // Omit duplicate results
    foreach($data as $key => $value) {
        $data[$key] = array_unique($data[$key]);
    }
    
    wp_reset_postdata();
    ?>

    And the html:

    <!-- Search Form (Small) -->
    <div class='search-form-wrap'>
    <div class='search-form'>
        <h2>Find a Holiday</h2>
        <form role="search" action="<?php echo site_url('/'); ?>" method="get">
            <!-- Choose Location -->
            <select name='location'>
                <option value='' disabled selected>Choose Location</option>
                <?php
                    foreach($data['locations'] as $location) {
                        echo "<option value='{$location}'>{$location}</option>";
                    }
                ?>
            </select>
    
            <!-- Choose Activity -->
            <select name='activity'>
                <option value='' disabled selected>Choose Activity</option>
                <?php
                    foreach($data['activity'] as $activity) {
                        echo "<option value='{$activity}'>{$activity}</option>";
                    }
                ?>
            </select>
    
            <!-- Choose Grade -->
            <select name='grade'>
                <option value='' disabled selected>Choose Grade</option>
                <?php
                    foreach($data['difficulty'] as $difficulty) {
                        echo "<option value='{$difficulty}'>{$difficulty}</option>";
                    }
                ?>
            </select>
    
            <!-- Choose Month -->
            <select name='month'>
                <option value='' disabled selected>Choose Month</option>
                <?php
                    foreach($data['months'] as $month) {
                        echo "<option value='{$month}'>{$month}</option>";
                    }
                ?>
            </select>

    Any help would be greatly appreciated as I’m a bit stumped by this. I’ve checked the original documentation for ACF and if I was building from scratch I would start there, but because I’m picking up a existing project I’m hoping there’s a solution that’s not too invasive.

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

  • Hi, I’m trying to create a search form using ACF and it looks like the code you have used will work well. Do you mind sharing how you got this to work? I’m stumped.

    Thanks

  • Hi Nixpix,

    This problem has been a stop-start issue for me. The above solution I’ve submitted does work (kind of) however I didn’t explain how the search function is working. If you can submit some details to me about your problem, what you’re inputting and trying to output it’ll help me offer you a solution.

    I’m a bit busy this week but when I get a chance I’ll create a post for you about what the whole search function is doing step-by-step.

    Thanks,

    Steve

  • I can’t seem to view your reply, can you repost please.

  • Apologies it was set to private, I think you should be able to view it now

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

The topic ‘How to sort/order select values from ACF field’ is closed to new replies.