1

I am using this code to get all posts sorted alphabetically in a given category, it works, but I feel the code can be improved...

<?php
$cats = get_categories('include=5');
foreach ($cats as $cat) {
    echo "<ul>";
    $args        = array(
        'cat' => 5,
        'posts_per_page' => -1,
        'orderby' => 'title',
        'order' => 'ASC'
    );
    $custom_loop = new WP_Query($args);
    while ($custom_loop->have_posts()) {
        $custom_loop->the_post();
        $category = get_the_category();
        // Only display a post link once, even if it's in multiple categories
        if ($category[0]->cat_ID == $cat->cat_ID) {
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
    }
    echo "</ul>";
}
wp_reset_query();

What do you think?

1

You are already passing category in $args. so not need to use get_categories(). You can use below code.

   $args = array(
        'cat' => 5,
        'posts_per_page' => -1,
        'orderby' => 'title',
        'order' => 'ASC'
    );
    $custom_loop = new WP_Query($args);
    if ($custom_loop->have_posts()) {
       echo "<ul>";
        while ($custom_loop->have_posts()) {
            $custom_loop->the_post();
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
       echo "</ul>";
   }
   wp_reset_query();
  • 1
    It worked, thanks! – Jack Nov 23 '19 at 9:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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