Category Archives: PHP

WordPress Query: sort by meta_key && compare by meta_key

I needed to run a query that pulled all posts that had a specific value ( or values ), and sort them by another meta key.

The custom fields (meta keys) I am using in this example are:
  • Age
  • Favorite_Color
The Requirements:
  • Sort by “Age”, showing the youngest first.
  • Show all posts that have Favorite_Color == to $favorite_color.
    • Note: $favorite_color can be an array that has multiple colors.
Here is the query I found that works!
	$args = array(
			'post_type' => 'custom_post_slug', // or 'posts' if you don't have one.
			'posts_per_page' => -1, // get ALL posts
			'order_by' => 'title',
			'title_li' => '',
			'order' => 'ASC',
			'meta_key' => 'age',
 			'orderby' => 'meta_value_num', // sort by age.  use 'meta_value' if the values aren't just numeric.
			'meta_query' => array(
				array(
					'key' => 'favorite_color', 
					'value' => $favorite_color,
					'compare' => 'IN'	// because $favorite_color might be an array.  This will look IN the array.
				)
			)
		);
$results = get_posts($args);

Hopefully this is helpful!

SOQL Queries: Handling GROUP BY aggregation with the Force.com PHP Toolkit

I needed to run a query and pull a distinct set of values. Easy in Force.com Explorer.
SELECT Field_Name FROM Table_Name GROUP BY Field_Name

Not so easy when querying though, as the result looks like this:
print_r($response->records); // print the response...

Array
(
    [0] => stdClass Object
        (
            [Id] => 
            [any] => <sf:Field_Name>Unique Value</sf:Field_Name>
        )

    [1] => stdClass Object
        (
            [Id] => 
            [any] => <sf:Field_Name>Unique Value 1</sf:Field_Name>
        )

    [2] => stdClass Object
        (
            [Id] => 
            [any] => <sf:Field_Name>Unique Value 2</sf:Field_Name>
        )

Okay… at least the response is unique.
Here’s a foreach to parse the results into a pretty array.
foreach($response->records as $record) {
     $results[] = strip_tags($record->any);
}

Now you have something to work with.
Array
(
    [0] => Unique Value
    [1] => Unique Value 1
    [2] => Unique Value 2
)