I'm trying to run a WP_Query - using a second database, the connection and results work just fine until I use tax_query and then no results are returned:

    $wpdb_backup = $wpdb;
    $wpdb = connect_to_site_DB();

    $args = array(
        'post_type' => 'publications',
        'post_status' => 'publish',
        'posts_per_page' => 40,
        'tax_query' => array(
                'taxonomy' => 'pub_type',
                'field' => 'slug',
                'terms' => 'review'

    $related_items = new WP_Query( $args );

    // loop over query
    if ($related_items->have_posts()) :
        echo '<h4>Related</h4><ul class="r_pubs">';
        while ( $related_items->have_posts() ) : $related_items->the_post();
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        echo '</ul>';

    // Reset Post Data
    $wpdb = $wpdb_backup;

Any thoughts would be most appreciated.

Thanks, D.

  • any luck using term_id instead of slug? – David Sword Apr 26 '18 at 18:45
  • What does connect_to_site_DB do? Note that this will play havoc with any kind of object caching system, and could lead to other weird results with WP_Cache in the same request as WP caches any info it gets via WP_Query and reuses it. Self inflicted cache poisoning. Perhaps you'd be better fetching this info on the frontend via the REST API in JS? – Tom J Nowell Apr 26 '18 at 18:48
  • Tom - thank you for your response. function connect_to_site_DB(){ global $wpdb; $wpdb = new wpdb( "user", "password", "db", "localhost" ); $wpdb->set_prefix('wp_'); return $wpdb; } I was thinking of looking into the REST API for this but thought I try this first – user142553 Apr 26 '18 at 20:25
  • @DavidSword - yes I tried with IDs, names and slugs - to no avail. – user142553 Apr 26 '18 at 20:28
  • Normally, when the WP_Query is not returning the expected results, I'd do echo $wpdb->last_error; to see if there was any MySQL errors. Next, I'd echo $related_items->request; to see if the SQL query was okay (means it was the expected query). Also, if the two databases share the same user, password and host, you could also try $wpdb->select( 'database_name' ); instead of creating a new wpdb() instance. Hope that helps. – Sally CJ Apr 27 '18 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.