Advanced CPT Filtering in WordPress

Prior to WordPress 3.1 you could only use one meta_key : meta_value : meta_compare in a query_posts. This meant that you could, for example, get the custom post type (cpt) product, filter it to get only those products that have a price >= 100. However you could not then orderby department ASC. Neither could you get the products with a price over 100 and colour green.
Now you can do advanced CPT filtering in WordPress since 3.1 with meta_query. There’s a nice intro post to this which I won’t repeat, but here is the code I used last week as an example:

$posts = get_posts(
	array(
		'numberposts' => -1,
		'post_type' => 'group_leader',
		'meta_query' => array (
			array(
				'key' => 'division',
				'value' => 'Cell',
				'compare' => '=' 
			)
		),
		'meta_key' => 'surname',
		'orderby' => 'meta_value',
		'order' => 'ASC'
	)
);
if($posts) { foreach($posts as $post) { //Do stuff } }

You can also have multiple query arrays within the main meta_query array for complex selections, eg:

'meta_query' => array (
	array( 'key' => 'division', 'value' => 'Cell', 'compare' => '=' ),
	array( 'key' => 'members', 'value' => '50', 'compare' => '>' )
),

This means you can finally filter Custom Posts properly, and by as many fields as you like.

Category:

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *