Please wait, loading...


Wordpress Display Posts From Category - Emerald Tech

September 2, 20130

A lot of times we need to display posts from a certain category on a page or a part of page. This is possible by using a bit of code in the relevant template file. For example if you need to display the posts from a category on homepage then edit the index.php (or any other file which has been set up as homepage in dashboard settings).

Display Posts by Category

Its easy to display posts by category using ‘wp_query’ object in code. You can easily use the arguments of the ‘wp_query’  to pass the category id and then display relevant posts. Now question is how to find the catagory id (which is a number) of a certain category. There two ways of doing that:

Two Ways of Finding Category ID in WordPress

1-Click on posts->categories and hover over the category name at the bottom of the screen you will see a link, which has a word call tag_id. See what is the value of tag_id and that gives you the category id.

2-Install the ‘reveal IDs’ plugin and it will show you catgory ID in front of category name on your category list page.

Using the wp_query object

Once you know the category id you can use wp_query object and pass it the category id for the posts to be displayed. First of all find the loop code in the template. The standard wordpress loop code is:

// The Loop
if ( have_posts() ) {
	while ( have_posts() ) {

Replace the above code with the code below, where category id will be the id which you have found for your category.

$query = new WP_Query( 'cat=4' ); //get all posts belonging to category id 4
// The Loop
if ( $query->have_posts() ) { //check if there are any posts in category 4
	while ( $query->have_posts() ) { //iterate through all posts in category 4

You can also display posts in categories by using other category parameters of wp_query object. For doing that replace the first line in above code with

Display posts that have this category (and any children of that category), using category slug:

$query = new WP_Query( 'category_name=staff' );
Display posts that have this category (not children of that category), using category id:

$query = new WP_Query( 'category__in=4' );

Any question? Ask me, i will be happy to help 🙂

Yumna Tatheer

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright @ Yamna Tatheer CEO Emerald Technologies Registration Number: 3520166158082