You should never use WP_Query
inside that kind of loop (there might be few exceptions but not in your case) because you can do most things with one query. This codex link has everything related to WP_Query
with explanations and very simple examples.
If taxonomies were a list of groceries and a trip to shop would be a query I doubt you would go to shop for each item separately. No, you will go once and buy them all.
Take a look at these examples and let me know if you’re having any problems.
//If you're using actual categories
$args = array(
'post_type' => 'portfolio',
'cat' => '2, 4, 5, 77, 1031' // Category IDs
);
//If you're using single custom taxonomy
$args = array(
'post_type' => 'portfolio',
'tax_query' => array(
array(
'taxonomy' => 'portfolio_tax',
'field' => 'term_id',
'terms' => array( 2, 4, 5, 77, 1031 ) // Term IDs
)
)
);
//If you're using multiple custom taxonomies
$args = array(
'post_type' => 'portfolio',
'tax_query' => array(
'relation' => 'AND', // Relation can be 'AND' or 'OR'
array(
'taxonomy' => 'portfolio_tax',
'field' => 'term_id',
'terms' => array( 2, 4, 5, 77, 1031 ) // Term IDs
),
array(
'taxonomy' => 'second_tax',
'field' => 'term_id',
'terms' => array( 1, 3, 6, 81, 1251 ) // Term IDs
)
)
);
//Query itself with output
$query_results = new WP_Query( $args );
while( $query_results->have_posts() ) {
$query_results->the_post();
echo the_title() . '<br />';
}