Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active February 13, 2017 22:50
Show Gist options
  • Save tommcfarlin/fd1d1ec30785a82d7523 to your computer and use it in GitHub Desktop.
Save tommcfarlin/fd1d1ec30785a82d7523 to your computer and use it in GitHub Desktop.
[WordPress] How to use multiple instances of WP_Query to retrieve results with common meta data.
<?php
/* Look for all of the acme post types that are either public or private. We are
* assuming that public or private is specified in the $_POST collection and that the
* proper error handling has already been done.
*/
$args = array(
'post_type' => 'acme',
'meta_query' => array(
array(
'key' => $_POST['account-type'],
'value' => 1
)
)
);
$search_query = new WP_Query( $args );
// If there are results, then push the IDs into an array
$account_types = array();
if ( $search_query->have_posts() ) {
while( $search_query->have_posts() ) {
$search_query->the_post();
array_push( $account_types, get_the_ID() );
}
}
wp_reset_postdata();
<?php
/* For ths post type we'll pull back all results that have a minimum and maximum value
* that sits between a specified range.
*
* Assume that $range has been defined elsewhere in the code where it would look something
* like this: array( 1000, 4000 );
*/
$args = array(
'post_type' => 'acme',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'minimum',
'value' => $range,
'type' => 'numeric',
'compare' => 'BETWEEN'
),
array(
'key' => 'maximum',
'value' => $range,
'type' => 'numeric',
'compare' => 'BETWEEN'
)
)
);
$search_query = new WP_Query( $args );
$min_max_values = array();
if ( $search_query->have_posts() ) {
while( $search_query->have_posts() ) {
$search_query->the_post();
array_push( $min_max_values, get_the_ID() );
}
}
wp_reset_postdata();
<?php
// Now push all of the arrays together, find their intersection, and make them unique to get our results
$results = array_unique ( array_intersect( $account_types, $min_max_values ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment