0
0
WordpressHow-ToBeginner · 4 min read

How to Query Posts by Category in WordPress

To query posts by category in WordPress, use the WP_Query class with the category_name or cat parameter. For example, new WP_Query(['category_name' => 'news']) fetches posts in the 'news' category.
📐

Syntax

The main way to query posts by category in WordPress is using the WP_Query class with specific parameters:

  • category_name: Use the category slug as a string to filter posts.
  • cat: Use the category ID as an integer to filter posts.
  • posts_per_page: Number of posts to return.

This lets you customize which posts to get based on categories.

php
<?php
$args = [
    'category_name' => 'news', // category slug
    'posts_per_page' => 5
];
$query = new WP_Query($args);
?>
💻

Example

This example shows how to query posts from the category with slug 'news' and display their titles in a list.

php
<?php
$args = [
    'category_name' => 'news',
    'posts_per_page' => 3
];
$query = new WP_Query($args);

if ($query->have_posts()) {
    echo '<ul>';
    while ($query->have_posts()) {
        $query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    echo 'No posts found in this category.';
}
wp_reset_postdata();
?>
Output
<ul><li>Post Title 1</li><li>Post Title 2</li><li>Post Title 3</li></ul>
⚠️

Common Pitfalls

Common mistakes when querying by category include:

  • Using the category name instead of slug in category_name.
  • Not calling wp_reset_postdata() after custom queries, which can break other loops.
  • Confusing cat (category ID) with category_name (slug).
  • Not checking if posts exist before looping, causing errors.
php
<?php
// Wrong: Using category name instead of slug
$args_wrong = [
    'category_name' => 'News', // Should be lowercase slug 'news'
];

// Right: Using slug
$args_right = [
    'category_name' => 'news',
];

// Always reset post data after custom query
$query = new WP_Query($args_right);
if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // output post
    }
}
wp_reset_postdata();
?>
📊

Quick Reference

Summary tips for querying by category in WordPress:

  • Use category_name for category slug, cat for category ID.
  • Always check have_posts() before looping.
  • Call wp_reset_postdata() after custom queries.
  • Use posts_per_page to limit results.

Key Takeaways

Use WP_Query with 'category_name' or 'cat' to filter posts by category.
Always check if posts exist with have_posts() before looping.
Call wp_reset_postdata() after your custom query loop to avoid conflicts.
Use category slugs (lowercase, no spaces) with 'category_name', not category names.
Limit posts returned with posts_per_page for better performance.