0
votes

I want my WP_Query to display six posts in total from across all categories listed in the array at random.

The loop/Query I have written only displays posts from the first category (Art) in the array.

What have I got wrong?

<div class="main-news">
			<!-- Define our WP Query Parameters -->
			<?php $the_query6 = new WP_Query(array('posts_per_page' => 6, 'category_name' => 'Art' , 'Technology', 'Fashion-Beauty')); ?>

			<!-- Start our WP Query -->
			<?php while ($the_query6 -> have_posts()) {
			 $the_query6 -> the_post(); ?>
				<div class="new-content">
				<!-- Display the Post Image with Hyperlink -->
					<div class="new-image"><?php the_post_thumbnail('fashion');?></div>
					<div class="new-content-excerpt">
					<!-- Display the Post Category Hyperlink -->
						<h5><?php 
						foreach((get_the_category()) as $category) {
						echo $category->cat_name . ' ';
						}
						?></h5>

						<!-- Display the Post Title with Hyperlink -->
						<h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
					</div>
				
				</div>
				<!-- Repeat the process and reset once it hits the limit -->
			<?php } ?>
			<?php wp_reset_postdata(); ?>
		</div>
2
Did you tried replacing 'category_name' => 'Art' , 'Technology', 'Fashion-Beauty') (which is not valid anyway) by 'category' => id_of_the_category? - user4121362
The WP Codex seems to think category_name is ok. But I shall try category ID instead. Thanks :) - Gavin Reynoldson
It should be an array of category slugs ('category_name' => array('art', 'technology', 'fashion-beauty'), you were not creating one. - user4121362

2 Answers

0
votes

Putting the category in an array of category IDs seemed to fix the situation.

I used the following code:

<?php $the_query6 = new WP_Query(array('category__in' => array( 240, 243, 239, ),'posts_per_page' => 4)); ?>

0
votes

The culprit line is the following:

<?php $the_query6 = new WP_Query(array(
    'posts_per_page' => 6, 
    'category_name' => 'Art', 
    'Technology', 
    'Fashion-Beauty')
); ?>

To extract the posts belonging to different categories, the following format must be used (read more about it on WordPress' documentation) :

  • Posts in one of the categories: 'category_name' => 'art,technology,fashion-beauty'
  • Posts in both categories: 'category_name' => 'art+technology+fashion-beauty'