Support

Account

Home Forums General Issues retrieving a list of post titles with a certain ACF value Reply To: retrieving a list of post titles with a certain ACF value

  • Not sure if this is what you’re after:
    This goes in your template:

    <?php 
    // args
    $args = array(
    	'posts_per_page'	=> -1,
    	'post_type'		=> 'your_cpt',
    	'meta_key'		=> 'location',
    );
    
    // query
    $the_query = new WP_Query( $args );
    
    if( $the_query->have_posts() ):
    	$countries = array();
    	while( $the_query->have_posts() ) : $the_query->the_post();
    		$countries[] = get_field('country');
    	endwhile;
    endif; 
    wp_reset_query();	 // Restore global post data stomped by the_post().
    
    // remove duplicates
    $country_list = array_unique($countries);
    
    if( $country_list ):
    	foreach( $country_list as $country ): ?>
    	<p><a href="#" class="country" country="<?php echo $country; ?>"><?php echo $country; ?></a></p>
    	<?php endforeach;
    endif;
    ?>
    <div id="ajax_countries_results"></div><!-- /ajax results -->
    

    Either add to your footer or enqueue the script

    
    <script>
    //filter the case studies
    jQuery(function($){
    	$('.country').click(function(){
    		
    		var country = jQuery(this).attr("country");		
    		
    		$.ajax({
    			type        : "POST",
    			data		: { action : 'get_country_posts', country: country }, 
    			dataType	: "html",
    			url			: '<?php echo admin_url('admin-ajax.php');?>', 
    
    			success     : function(data) {
    				//alert(this.data);
    				jQuery("#ajax_countries_results").html(data);
    				//console.log("success! country: " + country);
    			},
    			error       : function(xhr, status, error) {
    				var err = eval("(" + xhr.responseText + ")");
    				alert(err.Message);
    			}
    		});
    		return false;
    	});
    });
    </script>
    

    Then in your functions file

    
    <?php
    function get_country_posts() {
    	
    	$country = $_POST['country'];
    	
    	$args = array(
    			'post_type' 		=> 'your_cpt',
    			'post_status'		=> 'publish',
    			'posts_per_page'	=> -1, // show all posts.
    			'order'				=> 'DESC',
    			'meta_key'			=> 'location',
    			'meta_value'		=> $country	
    	);
    			
    	
    	$query = new WP_Query( $args );
    	if( $query->have_posts() ) : 
    
    		while( $query->have_posts() ): $query->the_post(); ?>
    		<p><?php the_title(); ?></p>
    		<?php endwhile;  wp_reset_postdata();
    
    	endif;
    	
    	die();
    
    }
    // Fire AJAX action for both logged in and non-logged in users
    add_action('wp_ajax_get_country_posts', 'get_country_posts');
    add_action('wp_ajax_nopriv_get_country_posts', 'get_country_posts');

    You need to amend the custom post type and your ACF fields but may help get you underway

    Code is untested!