How to Display Posts from a Specific Category in WordPress

The tutorial I am sharing with you today is more of an advanced tutorial, for persons who know their way around WordPress already. I am going to show you how to display the most recent posts from a specific category. This is particularly useful when creating magazine style themes.

Backstory on how this idea came about

A while back I had a client approach me and asked if it was possible to prevent posts from certain categories to show up on the homepage, because for whatever reason they felt it would be better for persons to check the category page if they wish to view those posts. Anyway, I decided to check it out and here is the result of those many, many, many hours.

I assume you already have your .php file setup and ready to go so here is the code:

<?php if ( have_posts() ) : ?>


  //Protect against arbitrary paged values (helps prevent same posts showing on all pages)

 $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;

  // Category selection array (This is where you select how much posts should be shown and from which categories; you can also place "-" in front of a category name to exclude just that category)

 $args = array( 'posts_per_page' => 7, 'category_name' => 'Uncategorized', 'paged' => $paged );

 $posts_array = get_posts( $args ); ?>

  // Post Loop (This varies significantly from the usual while loop in WordPress but works the same)

  <?php foreach ( $posts_array as $post ) : setup_postdata( $post ); ?>

    <?php get_template_part( 'content', get_post_format() ); ?>

  <?php endforeach; ?>

  // Resets the WordPress Loop (This is a necessary step)

 <?php wp_reset_postdata(); ?>

  // Theme navigation (TwentyThirteen Theme)

 <?php twentythirteen_paging_nav(); ?>

  // Usual Stuff
<?php else : ?>

 <?php get_template_part( 'content', 'none' ); ?>

<?php endif; ?>

This piece of code is vital to the news style layout, where you could essentially do this for each category and display the most recent news from each category separately on the same page.

There are many different variations of this snippet of code, some using “WP_Query” and others using “query_posts” now while those work similarly to the code above one thing to note is that neither of those variations support pagination, now if that is vital, the above code is pretty much your best bet.

Sources Support Forum
WordPress Codex
Ali Jafarian