This is the code I've been using, with the preceding query parameters excluded for brevity. As you can see, this comes from a widget that displays a grid of posts. The problem is that I can't figure out how to write a query, or multiple queries, that will retrieve the latest post from each of the six categories in a way that works.
$r = new WP_Query( apply_filters( 'widget_posts_grid', $query ) );
if ( $r->have_posts() ) :
?>
<?php echo wp_kses_post( $args['before_widget'] ); ?>
<?php
if ( $title ) {
echo wp_kses_post( $args['before_title'] . $title . $args['after_title'] );
}
?>
<div class="posts-grid">
<div class="row">
<?php while ( $r->have_posts() ) : $r->the_post(); ?>
<div class="col-md-4 col-sm-6">
<?php get_template_part( 'content', get_post_format() ); ?>
</div>
<?php endwhile; ?>
</div>
</div>
<?php echo wp_kses_post( $args['after_widget'] ); ?>
<?php
wp_reset_postdata();
endif;
I have tried a foreach loop with array_merge, but the result apparently can't be looped through...
$do_not_duplicate = array();
$r = new WP_Query();
$categories = get_categories();
foreach ( $categories as $category ) {
$args = array(
'cat' => $category->term_id,
'post_type' => 'post',
'posts_per_page' => '1',
'post__not_in' => $do_not_duplicate
);
$little_array = new WP_Query( $args );
$r = array_merge( $r, $little_array->posts );
while ( $r->have_posts() ) { $r->the_post();
$do_not_duplicate[] = $post->ID;
}
}
$r->post_count = count( $r->posts );
for($i = 1; $r->have_posts(); $i++) {
$r->the_post();
}
if ( $r->have_posts() ) :
From my research, I really thought this would work. However, it seems that after $r = array_merge( $r, $little_array->posts );
, $r
comes up empty. print_r($r);
prints nothing.
I appreciate the help.
For reference, this is the code that follows the above query:
if ( $r->have_posts() ) :
?>
<?php echo wp_kses_post( $args['before_widget'] ); ?>
<?php
if ( $title ) {
echo wp_kses_post( $args['before_title'] . $title . $args['after_title'] );
}
?>
<div class="posts-grid">
<div class="row">
<?php while ( $r->have_posts() ) : $r->the_post(); ?>
<div class="col-md-4 col-sm-6">
<?php get_template_part( 'content', get_post_format() ); ?>
</div>
<?php endwhile; ?>
</div>
</div>
<?php echo wp_kses_post( $args['after_widget'] ); ?>
<?php
wp_reset_postdata();
endif;