I’m developing a simple wordpress site. I’ve created a home page named home.php and trying to dynamically display posts separately according to category. the code is the following:
<?php get_header(); ?> <main id="main" class="row"> <?php $categories = ['politics' => 'রাজনীতি', 'finance' => 'অর্থনীতি', 'sports' => 'ক্রীড়া', 'entertainment' => 'বিনোদন', 'fenii' => 'আমাদের ফেনী', 'religion' => 'ধর্ম', 'literature' => 'সাহিত্য', 'study' => 'পড়া-লেখা', 'quiz' => 'কুইজ', 'zodiac' => 'রাশিফল']; foreach($categories as $key => $category): $query_args = array( 'post_type' => 'post', 'post_status' => 'publish', 'order' => 'DESC', 'orderby' => 'date', 'posts_per_page' => 3, 'ignore_sticky_posts' => true, 'category_name' => $category, ); $query = new WP_Query( $query_args ); ?> <section id="<?php echo $key ?>" class="col-sm-6 section"> <h3 class="title"> <?php echo $query->query['category_name'] ; ?> </h3> <?php if ( $query->have_posts()): while ( $query->have_posts() ): $query->the_post(); ?> <h5><a href=" <?php the_permalink() ?> "> <?php the_title() ?> </a> </h5> <a href="<?php the_permalink() ?>"> <p><?php the_excerpt() ?></p> </a> <?php endwhile; echo "<hr />"; wp_reset_postdata(); else: echo "<h6> Sorry! No post has been found of this type. </h6>"; echo "<hr />"; endif; ?> <hr /> </section> <?php endforeach; ?> </main> <?php get_footer(); ?>
But, no post is displayed like the following:
So, how can I display my posts according to category dynamically by foreach loop as I’ve been trying since the beginning?
Thank you.
Advertisement
Answer
Have you tried using category_id
as the argument for category instead of category_name
in your $query_args
?
Also, you should get your categories dynamically instead of creating the array for categories manually. Otherwise, you’ll have a problem if you add or remove categories in the future. Have a look at https://developer.wordpress.org/reference/functions/get_categories/.