Order by Category and Post in WP custom Query

To do this you have first get all the category in ascending order by
get_categories then you have to pass the cat_id in
WP_Query to get the post related with that category.

$args_cat = [
    'orderby' => 'name',
    'order' => 'ASC',
    'hide_empty' => 0,
];

$categories = get_categories($args_cat);
//print_r($categories);

if (!empty($categories)):
    foreach ($categories as $category):
        $args = [
            'post_type' => 'post',
            'posts_per_page' => -1,
            'order' => 'ASC',
            'orderby' => 'title',
            'cat' => $category->term_id
        ];

        $query = new WP_Query($args);
        while ($query->have_posts()) : $query->the_post();
            //You code
            the_title();
        //...
        endwhile;
        wp_reset_postdata(); // reset the query 
    endforeach;
endif;

Hope this helps!

Leave a Comment