Eliseo Montefalcon
Eliseo Montefalcon

Reputation: 13

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);

?>

Upvotes: 1

Views: 5229

Answers (2)

rnevius
rnevius

Reputation: 27092

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 );
}

Upvotes: 4

SergeyAn
SergeyAn

Reputation: 764

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);

Upvotes: 0

Related Questions