nazly.me

Weblog of Nazly Ahmed

Nazly Ahmed

Nazly Ahmed

Web Developer. PHP Addict. Wordpress Hacker. FOSS Enthusiast. (Micro)Blogger. Photo Hobbyist. Cricket Fanatic. Husband. Dad.

Since WordPress 3.0 introduced Custom Post Types, I have been using it extensively in my projects. Each Custom Post Type had multiple Custom Fields, but I had major concerns on building an algorithm to search across multiple Custom Fields using query_posts() since it allowed only a single key value pair (meta_key and meta_value). I had to extend the functionality of query_posts() to get over this problem. Looking at the documention it appears that with the release of WordPress 3.1, query_posts() will have a new parameter called meta_query which could handle multiple Custom Fields.

Prior to WordPress 3.1, query_posts() can only be used to search a single key or value using meta_key and meta_value parameters. meta_compare parameter can be used to specify the comparison between them.

<?php
query_posts( array(
                            'meta_key' => 'price',
                            'meta_value' => '22',
                            'meta_compare' => '<=',
                            'post_type' => 'product'
                          )
                );
?>

With the release of WordPress 3.1, the introduction of meta_query parameter to query_posts() allows developers to extend the search across multiple Custom Fields.

<?php
$args = array(
	'post_type' => 'product',
	'meta_query' =>
		array(
			'key' => 'color',
			'value' => 'blue',
			'compare' => 'NOT LIKE'
		),
		array(
			'key' => 'price',
			'value' => array( 20, 100 ),
			'type' => 'numeric',
			'compare' => 'BETWEEN'
		)
)
query_posts( $args );
?>

Happy Coding!

Posted on 6th February 2011 19:12:12