Custom order for categories in a loop?

I am displaying categories and posts on a page belonging to a Parent category. Here in this code sample, I am getting all the child categories of CategoryID 25, looping through them, and displaying the posts associated with each child.

The child categories are displayed alphabetically. I’d like to find a way to set a custom order — perhaps by specifying an array of their IDs and using that to display them in the order I want?

I’m familiar with ways to do this with posts, with custom meta data or ACF, but don’t know how to achieve this with categories.

<?php
$paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
$cat_id = 25;
$child_categories = get_categories(
array(‘parent’ => $cat_id)
);
foreach ($child_categories as $child) { ?>
<!– loop through child categories and make columns –>
<div class=”col-sm-4″>
<!– category title –>
<?php
$string = $child->cat_name;
$className = preg_replace(‘/[^A-Za-z0-9-]/’, ”, $string);
?>
<h2 class=”cat-icon <?php echo $className; ?>”><?php echo $child->cat_name; ?></h2>

<!– description –>
<div class=”cat-description”>
<?php echo category_description($child); ?>
</div>

<?php $args = array(‘cat’ => $child->term_id, ‘posts_per_page’ => -1, ‘paged’ => $paged, ‘orderby’ => ‘title’, ‘order’ => ‘ASC’);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<?php get_template_part(“home”, “service-card”); ?>
<?php endwhile; ?>
</div>
<?php
} ?>
<?php wp_reset_query(); ?>

Read more here:: Custom order for categories in a loop?

Leave a Reply

Your email address will not be published. Required fields are marked *