How to display Wordpress Custom Posts according to Category using WP_Query

Check out my other posts and tutorials on Web Development!

We recently did a complete overhaul of our website design and content. When redesigning our FAQ page, I decided to opt for a custom post type rather than using shortcodes. The goal was to sort the FAQ posts by category and then loop through each post for said category.

This can be accomplished by the following:

First, Pull the Categories

<?php // get the categories for the custom post taxonomy
    $terms = get_terms( 'faqs_cat', array(
            'orderby'    => 'id',
            'hide_empty' => 1 // hide categories with no posts
        ) 
    );
?>

Then, Loop Through Posts by Category

<?php // now run a query for each category
foreach( $terms as $term ) {

    // Define the query
    $args = array(
        'post_type' => 'faq', // replace with name of your custom post type
        'faqs_cat'  => $term->slug // replace with name of your custom taxonomy
    );
    $query = new WP_Query( $args );

    // output the category in a heading              
    echo'<h2 class="h2 faq-cat">' . $term->name . '</h2>';

        // Start the post loop
        while ( $query->have_posts() ) : $query->the_post(); ?>

        <?php /* display the post as you see fit */ ?>
        <div id="post-<?php the_ID(); ?>" class="faq-item">
            <h5><?php the_title(); ?></h5>
            <div><?php the_content(); ?></div>
        </div>

        <?php endwhile;
        echo '<hr/>';

    // use reset postdata to restore the original query
    wp_reset_postdata();

} ?>

Hope you found this useful! Be sure to check out our FAQ page to see it in action.

One Response to How to display WordPress Custom Posts according to Category using WP_Query

  1. This is probably a seriously noob type of question, but I’ve been pulling my hair out trying to do something similar with a custom post type that uses the standard WordPress categories. What syntax should I use in place of your custom taxonomy?

    Thanks for any help you can provide!

    Reply

Leave a Reply

Contact Us

Subscribe

Subscribe to our blog to receive latest news and tutorials on Web Design, Development, SEO, and more!