Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/*
* Example code showing how to hook WordPress 3.0 to allow for querying multiple meta_keys.
* It uses this approach for setting criteria where the keys get array indexed (the following
* query will query a hypothetical list of products for those colored Red and sized Large
* and it will sort them in price order:
*
* WP_Query('post_type=product&meta[color]=Red&meta[size]=Large&meta_key=price&orderby=meta_value_num')
*
* To try this example:
*
* 1. Modify this example $post_type and $meta_query.
* 2. Name the edited file "test.php" and put in the root of your website.
* 3. Test it by typing one of this URL into your browser using your domain instead of "example.com":
*
* a. http:/example.com/test.php
*
* This example was written in response to this question:
*
* http://wpquestions.com/question/show/id/691
*
* By:
*
* Mike Schinkel (http://mikeschinkel.com/custom-wordpress-plugins/)
*
* NOTE:
*
* The use of $_GET in this manner is inherently insecure. The values need to be sanitized before
* begin used but for the purpose of this example we'll use them for simplicity since this example
* is not about sanitizing $_GET parameters.
*
* This example is licensed GPLv2.
*
*/
include "wp-load.php";
add_filter('posts_where','multiple_meta_criteria_posts_where',10,2);
$post_type = 'post';
$meta_query = 'meta_key=Retail_Price&orderby=meta_value_num&meta[foobar]=&meta[product_brand]=' . $_GET['brandName'];
$base_query = "post_type=$post_type&posts_per_page=-1&order=" . $_GET['order'];
$posts = new WP_Query("$meta_query&$base_query");
echo "<h1>Query:</h1>";
echo '<pre>';
parse_str($posts->query,$query);
print_r($query);
echo '</pre>';
echo "<h2>Results:</h2>";
while ( $posts->have_posts() ):
$posts->the_post(); ?>
<h3 id="post-<?php the_ID(); ?>" <?php post_class(); ?>><?php the_title(); ?></h3>
<?php the_content();
endwhile;
function multiple_meta_criteria_posts_where($where,$wp_query) {
if (isset($wp_query->query)) {
$query = $wp_query->query;
if (is_string($query))
parse_str($query,$query);
if (is_array($query)) {
global $wpdb;
foreach($query as $param_key => $param_value) {
if ($param_key=='meta') {
foreach($param_value as $key => $value) {
if (!empty($value)) {
$sql = " AND {$wpdb->posts}.ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key=%s AND meta_value=%s) ";
$where .= $wpdb->prepare($sql,$key,$value);
}
}
}
}
}
}
return $where;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.