Custom Select Query by two meta keys
-
Hello, I am trying to make a query that will display posts containing exactly the same value from two or more meta_keys;
for example display all products with blue color and 10kg
I only made the query based on one key value, and it works
<?php global $wpdb; global $post; $querystr = " SELECT wposts.* FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = 'color' AND wpostmeta.meta_value = 'blue' AND wposts.post_type = 'post' ORDER BY wpostmeta.meta_value DESC "; $pageposts = $wpdb->get_results($querystr, OBJECT); ?> <?php if ($pageposts): ?> <?php global $post; ?> <?php foreach ($pageposts as $post): ?> <?php setup_postdata($post); ?> <div class="post" id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"> <?php the_title(); ?></a> </div> <?php endforeach; ?> <?php endif; ?>
How to make a query now that will show posts based on two or more keys and values, but the displayed post must have exactly all the values in the query, not only one.
I made the following code, but it is not working
<?php global $wpdb; global $post; $querystr = " SELECT wposts.* FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta LEFT JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id WHERE wposts.ID = wpostmeta.post_id AND ((wpostmeta.meta_key = 'color' AND wpostmeta.meta_value = 'blue') AND (wpostmeta.meta_key = 'weight' AND wpostmeta.meta_value = '10')) AND wposts.post_type = 'post' ORDER BY wpostmeta.meta_value DESC "; $pageposts = $wpdb->get_results($querystr, OBJECT); ?> <?php if ($pageposts): ?> <?php global $post; ?> <?php foreach ($pageposts as $post): ?> <?php setup_postdata($post); ?> <div class="post" id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"> <?php the_title(); ?></a> </div> <?php endforeach; ?> <?php endif; ?>
What to change?
Thank you
- The topic ‘Custom Select Query by two meta keys’ is closed to new replies.