Advanced Metadata Queries

WordPress 3.1 will come with powerful taxonomy querying capabilities.

It will also have comparable capabilities for querying posts based on various custom fields.

Scenario

You have a ‘product’ custom post type with ‘price’ and ‘description’ custom fields.

Before

Here is the most advanced meta query that you could do out of the box, before WP 3.1:

Get all the products with a price greater than 100:

query_posts( array(
  'post_type' => 'product',
  'meta_key' => 'price',
  'meta_value' => 100,
  'meta_compare' => '>'
) );

After

Here is what you can do now:

Get all the products with a price between 100 and 200 and a description that doesn’t contain the string ’round’:

query_posts( array(
	'post_type' => 'product',
	'meta_query' => array(
		array(
			'key' => 'price',
			'value' => array( 100, 200 ),
			'compare' => 'BETWEEN',
			'type' => 'numeric',
		),
		array(
			'key' => 'description',
			'value' => 'round',
			'compare' => 'NOT LIKE'
		)
	)
) );

A breakdown of the enhancements:

A complete reference can be found in the Codex: WP_Query#Custom_Field_Parameters

Having read this, please don’t use custom fields as taxonomies.

comments powered by Disqus