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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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