Use WP_Query with a custom SQL query

You won’t be able to translate a complicated SQL query directly to a WP_Query. What you can do is return Post IDs from the SQL and pass those IDs into the WP_Query args. Do note that this is highly inefficient and will likely create slow queries as post__in is not fast.

You need to modify the SQL to include the post ID:

SELECT p.ID, p.post_name, /*... etc... */

Next we want to tell wpdb::get_results() to return an array so we can parse out the IDs:

$results = $wpdb->get_results( $sql, ARRAY_A );

Next we want to use wp_list_pluck() to grab the IDs of the results:

$post_ids = wp_list_pluck( $results, 'ID' );

Finally, we can pass these IDs into the posts__in parameter of WP_Query:

$query = new WP_Query( array(
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'post__in'      => $post_ids,
) );

If you also want to get the terms you’ll need to either get the term slugs or the term IDs.

You need to modify the SQL to include term IDs. Since you have multiple taxonomies you’ll need to alias these differently:

SELECT /* ... etc... */ t.term_id as storyline_term_id, t2.term_id as company_term_id

Next we want to use wpdb::get_results() to return an array so we can parse out the term IDs:

$results = $wpdb->get_results( $sql, ARRAY_A );

Next we want to use wp_list_pluck() to grab the term IDs of the results:

$story_term_ids = wp_list_pluck( $results, 'storyline_term_id' );
$company_term_ids = wp_list_pluck( $results, 'company_term_id' );

Finally, we can get the terms by IDs:

$story_terms = get_terms( array(
    'taxonomy'      => 'storylines',
    'object_ids'    => $story_term_ids,
) );

Leave a Comment