WP Query Posts or Pages By Category

Complexity Low
Compatibility WordPress 5.4, 5.5+

Overview

By default WordPress allows you to categorize your content. This functionality is extremely powerful and allows you to have full control of your content. Using this recipe will allow you to find all posts (custom or pages) that are in the same category. This will allow you to build recommended reading sections, customize your archive pages, or whatever other functionality you can come up when grouped by category.

Step 1: Build the Category Query with WP Query

Add this query to the template you wish to load posts by category:

<?php
    $args = [
        'post_type' => 'post', // Could be `page` or Custom Post Type
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field'    => 'name',
                'terms'    => 'industries',
            ),
        ),
    ];

    $industriesCategoryQuery = new WP_Query( $args );

We used a sample category named "Industries" with a slug of "industries". You can customize this query in any way you feel necessary using the appropriate arguments for WP Query. The tax_query is where we filter by category.

Step 2: Use the Results

Use the following to iterate over the results:

<?php
    while( $industriesCategoryQuery->have_posts() ){
        $industriesCategoryQuery->the_post();

        // You now have access to $post and methods like the_title();
    }

Usage Ideas

  • Display lists of posts by category on a category page
  • Find similar posts or recommended reading

Similar Recipes