3 posts from each existing category on one page

Question

The following is not working…

<?php $categories = get_categories( array(
'orderby' => 'name',
'parent'  => 0
) ); 
foreach($categories as $category):
    
    $args = array(
    'cat' => $category->name,
    'posts_per_page' => 3,);
    $category_posts = new WP_Query( $args );

    if( $category_posts->have_posts() ): ?>
            
        <h2><?php echo $category->name; ?></h2>
        
        <div class="row">
        <?php  while( $category_posts->have_posts() ):
            $category_posts->the_post(); ?>
        
            <div class="blog-post-tile" style="background-image: url(<?php 
                echo get_the_post_thumbnail_url(get_the_ID(), 'full');?>)">
                            
                <h3 class="blog-post-tile__title">
                    <?php the_title(); ?>
                </h3>
                                
            </div>
        <?php endwhile; ?>          
        </div>
    <?php endif;
    wp_reset_postdata();
    wp_reset_query();
endforeach;

My goal is to display on one page 3 latest posts from all existing categories. By now this code displays for each category same posts. It reads good category names just it seems like query is not reseted and it show posts again… To be honest it works at the beginning but it looks like I changed something in the code and broke it. I can’t find solution again.

0
Piotr Orczyk 2 years 2020-10-24T05:10:19-05:00 0 Answers 10 views 0

Leave an answer

Browse
Browse