0

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

I found a problem. I had to change this:

$args = array(
    'cat' => $category->name,
    'posts_per_page' => 3,);

for this:

$args = array(
    'category_name' => $category->name,
    'posts_per_page' => 3,);

In first code I was passing category name which is string to argument expecting ID of category. Here is Codex reference where I found solution:

  • category_name (string) – use category slug.
  • category__and (array) – use category id.
  • category__in (array) – use category id.
  • category__not_in (array) – use category id.
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.