Jump to content

how to Query Posts by meta_key and sort


TCombs

Recommended Posts

I used custom fields for a series of real estate listing posts on a wordpress site.

 

I want to query all posts by the State they are listed in and sort them alphabetically. (custom field: property_locations_state)
Then I want to list the properties within that state. (custom field: property_name)

 

For example:

Indiana

  • property 1
  • property 2

Michigan

  • proptery 1
  • property 2

With the code below, I can see the posts by print_r($propposts), however, no results are being displayed. Please let me know if you can see what's wrong with this code.

 

<?php 
$args  = array(
	'posts_per_page' => -1,
	'meta_key' => 'property_locations_state',
	'meta_query' => array(
		array(
			'key' => 'property_locations_state'
		),
		array(
			'key' => 'property_name'
		))
  ); 
$propposts = get_posts($args);

//custom function for comparing the data we want to sort by  
function cmp($a, $b){  
  if ($a->property_locations_state == $b->property_locations_state) {  
    return 0;  
  }  
  return ($a->property_locations_state > $b->property_locations_state) ? 1 : -1;  
} 

usort($propposts, 'cmp'); 

$directory = array();
foreach ($propposts as $proppost ) { // get all the posts data     
$posttitle = get_post_meta($proppost->post_id);

if($posttitle){
foreach ($posttitle->property_locations_state as $title) {
$directory[$title][] = array ( 'property_name' => $posttitle->property_name );        
}
}

ksort($directory);  // sort by state
echo '<ul id="example1" class="accordion">';  
foreach ($directory as $state => $lists) { 

echo '<li><h3>' .$state. '</h3>';   
echo '<div class="panel loading">'; 
sort($lists);  // sort Properties by name
foreach ($lists as $list) { 	
		echo '<div id="membox">';
		echo $list['property_name'].'<br />';
 }
 echo '</div></li>';
}
echo '</ul>';
}

?>  

 

Link to comment
https://forums.phpfreaks.com/topic/275317-how-to-query-posts-by-meta_key-and-sort/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.