Wordpress - Get post with multiple meta keys and value
This should do it. The default relation is AND so that won't need to be specified.
$args = array(
'post_type' => 'wpse_cpt',
'meta_query' => array(
array(
'key' => 'post_code',
'value' => '432C',
),
array(
'key' => 'location',
'value' => 'XYZ',
),
),
);
$query = new WP_Query( $args );
$args = array(
'post_type' => 'wpse_cpt',
'meta_query' => array(
'relation' => 'AND' //**** Use AND or OR as per your required Where Clause
array(
'key' => 'post_code',
'value' => '432C',
),
array(
'key' => 'location',
'value' => 'XYZ',
),
),
);
$query = new WP_Query( $args );
Edit Again: Ah, I didn't answer the question. You would select a.*
to get all columns of the posts with the matching key values, instead of selecting c.meta_value
.
The below sql/$wpdb
query will select all meta_value%s
of a post with post_type of $postType
and a meta_key value of $metaKey
. Therefore selecting all the different values of a given meta_key (via '$metaKey'). The term_relationships
table is wordpress' helper table for relationship connections in tables. wp_posts
is the wordpress 'posts' table, and, wp_postmeta
is the wordpress 'postmeta' table. (Note: If you are using custom tables these table names would differ.)
~ Edited to add 'doing' notes, requested by @MikeNGarrett
/* $wpdb is a global var provided by the wordpress 'engine'
** for query'ing wordpress database tables.
*/
global $wpdb;
$postType = 'mycustomposttype';
$metaKey = 'mymetakey';
$query = "
SELECT c.meta_value
FROM wp_posts a
LEFT JOIN wp_term_relationships b
ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c
ON (a.ID = c.post_id)
WHERE a.post_type = %s AND c.meta_key = %s";
$metaValues = $wpdb->prepare(query, [$postType, $metaKey]);
$metaValues = $wpdb->get_results($metaValues);
Notes: I am just reusing the $metaValues variable. There is no other reason to write the results of $metaValues prepare()
back to the $metaValues variable. You do however have to pass $metaValues to get_resluts()
.