Custom category order with get_categories

I have a site with metro_creativex theme with side menu that displays categories in an alphabetic order. Now I need to sort them by my own order (that’s not alphabetical reverse or by id) and, since on my page it calls a function to display the side menu, on the function I foun this line that I already modified to show only the categories I needed:

$metro_creativex_terms = get_categories('hide_empty=0&exclude=1,22,23,24,49');

Now instead of telling it to not show empty categories and to hide some other categories by their id, I want to tell him to show categories in this exact order: 47, 44, 43, 45, 42, 41, 40, 25, 46. I also don’t need any other categories with those ones so I’m looking for a really rigid kind of order.
This is how the variable is used:

<?php
          $metro_creativex_terms = get_categories('hide_empty=0&exclude=1,22,23,24,49');

          if ($metro_creativex_terms) {
            foreach( $metro_creativex_terms as $metro_creativex_term ) {
                $metro_creativex_post_nr = $metro_creativex_term->count;
                if ( $metro_creativex_post_nr == "1" )
                    $metro_creativex_post_nr_display = "song";
                else {
                    $metro_creativex_post_nr_display = 'songs';
                }
              echo '
                <a href="' . get_category_link( $metro_creativex_term->term_id ) . '" class="color-code" title="' . $metro_creativex_term->name.'">
                    ' .'<span>'. $metro_creativex_term->name.'</span>'.'
                    <div class="read bg-code">
                        <p>'.$metro_creativex_post_nr.'</p><span>'.$metro_creativex_post_nr_display.'</span>
                    </div>
                </a>';
                }
          }
        ?>

Is it even possible to order categories by my custom order?

1 Answer
1

Exact order by category id on get_categories

@EliChan, by using get_categories, I don’t think it’s possible to exact order by id if you use exclude. It is better if use include as parameter of ids order and orderby with value include.

$args = array(
    'hide_empty' => 0,
    'orderby'    => 'include',
    'include'    => array( 47, 44, 43, 45, 42, 41, 40, 25, 46 ) //exact order id
);
$metro_creativex_terms = get_categories($args);

You can see get_terms for values accepted for $args.

Leave a Comment