0

I have a page that lists posts grouped by category. Here is the current code:

<?php

$cats = get_terms('category');

foreach ($cats as $cat) {
    $cat_id= $cat->term_id;

    echo "<h2>".$cat->name."</h2>";

    $custom_query = new WP_Query(
        array(
            'cat' => $cat_id,
            'post_type' => 'my_post_type',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        )
    ); ?>
    <ul>
    <?php if ($custom_query->have_posts()) : while ($custom_query->have_posts()) : $custom_query->the_post(); ?>
        <li><a href="<?php the_permalink();?>"><?php the_title(); ?></a></li>
    <?php endwhile; endif; ?>
    </ul>

<?php } ?>

Is there a more efficient way to do this without so many queries? I found this related question: Most efficient way to list all categories and display a post for each of them?. However, I'm not sure how to implement Milo's suggestion or if it would be applicable.

2
  • Fantastic. Exactly what I was looking for with a great explanation. Thanks @pieter-goosen!
    – ideaotel
    Commented Feb 3, 2015 at 19:35
  • I'm glad that post helped you. enjoy :-) Commented Feb 4, 2015 at 4:25

1 Answer 1

1

My suggestion would be to pass different arguments to Wp_Query Class.

using 'cat' property, passing category Ids.

<?php
    $custom_query = new WP_Query(
        array(
            'cat' => '1,2,3,4'
            'post_type' => 'my_post_type',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        )
    ); 
?>

OR using 'category_name' property passing category slug's as string parameters.

<?php
    $custom_query = new WP_Query(
        array(
            'category_name' => 'category1+category2'
            'post_type' => 'my_post_type',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        )
    ); 
?>

More info about Wp_Query parameters: http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

Hope it helps. Good Luck. Att

2
  • Hi Renato. Thanks for answering. However, as seen in my code, the posts should be grouped by category. Your solution just combines all posts into the same query without grouping.
    – ideaotel
    Commented Feb 2, 2015 at 22:46
  • @ideaotel, if you want to minimize your DB queries you need to pay for it in having a more complex code. Commented Feb 3, 2015 at 7:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.