Support

Account

Home Forums Front-end Issues Count field selection in a WP Query Reply To: Count field selection in a WP Query

  • There were 2 errors in the code:
    1) The second loop had post_type twice
    2) The wp_reset_query was in the wrong place

    $args = array( 
    	'post_type'         => 'cars',
    	'posts_per_page'    => -1,
    	'post_status' => 'publish',
    	'meta_query'    => array(
    		'post_type' => 'cars',
    		'post_per_page' => -1,
    		'post_status' => 'publish', 
    		'meta_query' => array(
    			array(
    				'key'       => 'sold',
    				'value'     => array('no'),
    				'compare'   => 'IN',
    			),
    		)
    	)
    );
    $wp_query = new WP_Query($args);
    if ($wp_query->have_posts()) :
    	$get_price = array();
    	while ($wp_query->have_posts()) : $wp_query->the_post();
    		$get_price[] = get_field('price');
    	endwhile;
    endif; #endif $wp_query
    
    echo '<pre>';
    print_r($get_price);
    echo '</pre>';
    
    $filter_price = array_unique($get_price);
    
    echo '<pre>';
    print_r($filter_price);
    echo '</pre>';
    
    if($filter_price):
    foreach($filter_price as $price):
    echo '<p>Price: '.$price.'</p>';
    
    	$args = array(
    		'post_type'         => 'cars',
    		'posts_per_page'	=> -1,
    		'meta_query'	=> array(
    			'relation'		=> 'AND',
    			array(
    				'key'		=> 'price',
    				'value'		=> $price,
    				'compare'	=> '<='
    			),
    		)
    	);
    	$wp_query = new WP_Query($args);
    
    	$figure_total = $wp_query->found_posts;
    	$count = count( $wp_query->get_posts() );	
    
    	echo '<p>$figure_total: '.$figure_total.' count: '.$count.'</p>';
    	wp_reset_query();
    
    endforeach;
    endif; #endif $filter_price

    I’ve tried the above code and it worked for me!