Query Multiple Arguments

I needed to query multiple post types and specific taxonomies and meta for a featured banner on a website, and found that using an array for post_type wasn’t working with the tax_query.

Here’s an example showing multiple arguments for a single loop using array_merge().

$banners = array(
	'post_type' => 'banner',
	'posts_per_page' => 3,
);
$events = array(
	'post_type' => 'tribe_events',
	'posts_per_page' => 3,
	'tax_query'      => array(array(
        'taxonomy'  => 'tribe_events_cat',
        'field'     => 'slug',
        'terms'     => 'promoted-event'
    )),
    'meta_query' => array(array(
        'key' => '_EventStartDate',
        'value' => current_time( 'Y-m-d' ),
        'compare' => '>='
    ))
);

$banners_query = new WP_Query( $banners );
$events_query = new WP_Query( $events );
$result = new WP_Query();

// start putting the contents in the new object
$result->posts = array_merge( $banners_query->posts, $events_query->posts );

$result->post_count = count( $result->posts );

if ($result->post_count) { ?>
	<div id="banner">
		<?php while($result->have_posts()) : $result->the_post(); 
			$large = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'large' ); ?>
			<div class="banner_content background-image" style="background-image: url(<?php echo $large[0]; ?>);">
				<div class="wrap">
					<div class="banner_content_inner">
						<div class="banner_content_background has-white-background-color">
							<h3 class="banner_title"><?php the_title(); ?></h3>
							<?php the_excerpt(); ?>
							<div class="wp-block-buttons">
								<div class="wp-block-button is-style-outline has-dark-grey-color">
									<a class="wp-block-button__link" href="<?php the_permalink(); ?>">
										LEARN MORE
									</a>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		<?php endwhile; ?>
	</div>
<?php }

Source.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.