Ordering get_categories() result by predetermined order

I want to know why get_categories() is auto ascending. I want to return an array, based on the order in which category IDs are included.

This is my code.

<?php

$args = array(
    'include'=> '5,4,7,6',
);
$cats = get_categories($args);

?>

Related posts

2 comments

  1. I’m not sure why you would use get_categories() at all, since you already know the order you’re looking for, as well as the target IDs.

    Instead, I would use get_category(), and generate the $categories array with a simple foreach loop:

    $categories = array();
    $cat_ids = array(5,4,7,6);
    
    // A simple foreach loop, to keep things in your required order
    foreach ( $cat_ids as $id ) {
        $categories[] = get_category( $id );
    }
    
  2. Here is the WordPress function reference

    wordpress function reference

    Basically you need to pass arguments array to the get_categories function

    $args = array(
      'orderby' => 'name',
      'order' => 'ASC',
      'include' => '5,4,7,6'
     );
    
    $categories = get_categories($args);
    

    EDIT:

    $args = array(
    'orderby' => 'ID',
    'order' => 'DESC',
    'include' => '5,4,7,6'
     );
    
    $categories = get_categories($args);
    

Comments are closed.