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.
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.
Share Improve this question asked Oct 24, 2020 at 10:01 Piotr OrczykPiotr Orczyk 111 bronze badge1 Answer
Reset to default 1I 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.