Search code examples
phpwordpressblogsposts

Get posts from category from custom query


I have the following custom WordPress query. This displays all the blog posts just fine.

<?php $mymain_query = new WP_Query( array( 'post_type' => 'post','posts_per_page' => '10' ) ); while($mymain_query->have_posts()) : $mymain_query->the_post(); ?>

    //shortened code below
    <div class="blog-post">
        <h5><?php the_title(); ?></h5>
        <p><?php the_content(): ?></p>
    </div>

<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>

But I when I plug this into archive.php it is still calling all blog posts instead of the ones in that category.

How can I edit my code to only show the blog posts in that specific category?


Solution

  • I figured it out. Here is my solution

    <?php 
        $categories = get_the_category();
        $category_id = $categories[0]->cat_ID;
        $mymain_query = new WP_Query( array( 'cat' => $category_id,'posts_per_page' => '10' ) ); while($mymain_query->have_posts()) : $mymain_query->the_post(); ?>
    
        //shortened code below
        <div class="blog-post">
            <h5><?php the_title(); ?></h5>
            <p><?php the_content(): ?></p>
        </div>
    
    <?php endwhile; ?>
    <?php wp_reset_postdata(); // reset the query ?>