Get Posts from a Category in WordPress

Posted on April 25, 2012 by Dan Doicaru in WordPress Category

In this tutorial you will learn how to get posts from a category and how many to show on the current page, using the function inside the loop.

First you need to know that this trick will work only inside a loop.

Custom Loop for Index Page

For example, if you want to display posts from a certain category, to your homepage, just update "index.php" with the lines below:

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

<?php query_posts('category_name=your_category'); ?>

<?php while (have_posts()) : the_post(); ?>

<!-- loop content will go here -->

<?php endwhile; ?>

Custom Loop with Show Posts per Page

If you want to display posts from a certain category and you want to control how many posts will be visible per page, just update "index.php" or "archive.php" with the lines below:

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

<?php query_posts('category_name=your_category&posts_per_page=10'); ?>

<?php while (have_posts()) : the_post(); ?>

<!-- loop content will go here -->

<?php endwhile; ?>

Show Posts from a Category by ID

For example, if you want to display posts from a certain category by id, just update "index.php" or "archive.php" with the lines below:

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

<?php query_posts('cat=3'); ?>

<?php while (have_posts()) : the_post(); ?>

<!-- loop content will go here -->

<?php endwhile; ?>

Related Articles
Comments
Hint: Wrap your code syntax (html, css or others) between <pre> and </pre> tags. All comments are moderated.


1 + 7 =

Search
Subscribe by E-mail

HTML-TUTS is created and maintained by Dan Doicaru.
This website is a rebrand to Extreme Design Studio (extremestudio.ro), built under WordPress platform.