Get Terms by IDs with IDs order

I want to get Terms by IDs with IDs order. But that doesn’t working, WP automatically change the order.

My code-

$catsArray = array(159, 155, 143, 153, ......);
$series = get_terms( array(
              'taxonomy' => 'ctc_sermon_series',
              'number'  =>  9,
              'offset'  =>  $offset,
              'include' => $catsArray,
              'hide_empty'  => false, 
            ) );

And result-

(
    [0] => WP_Term Object
        (
            [term_id] => 155
            [name] => 10
            [slug] => 10
            [term_group] => 0
            [term_taxonomy_id] => 155
            [taxonomy] => ctc_sermon_series
            Get Terms by IDs with IDs order => 
            [parent] => 0
            [count] => 1
            [filter] => raw
        )

    [1] => WP_Term Object
        (
            [term_id] => 159
            [name] => 14
            [slug] => 14
            [term_group] => 0
            [term_taxonomy_id] => 159
            [taxonomy] => ctc_sermon_series
            Get Terms by IDs with IDs order => 
            [parent] => 0
            [count] => 1
            [filter] => raw
        )

    [2] => WP_Term Object
        (
            [term_id] => 153
            [name] => Name 8
            [slug] => name-8
            [term_group] => 0
            [term_taxonomy_id] => 153
            [taxonomy] => ctc_sermon_series
            Get Terms by IDs with IDs order => Name 8 Des
            [parent] => 0
            [count] => 1
            [filter] => raw
        )

    [3] => WP_Term Object
        (
            [term_id] => 143
            [name] => Series 1
            [slug] => series-1
            [term_group] => 0
            [term_taxonomy_id] => 143
            [taxonomy] => ctc_sermon_series
            Get Terms by IDs with IDs order => Series 1 Description
            [parent] => 0
            [count] => 3
            [filter] => raw
        )

)

I expect the result of term with ID-159 first, but every time i get result of ID-155 first. I need to get result by ID’s array sequence.

Thanks in advance 🙂

2 s
2

So I believe the question is how to get the terms back in the order of the Ids you’ve provided – which might not be sorted ascending or descending, but a random order instead.

Surprisingly, I think there’s a shortcut for that in WP – who knew? This, I believe, is what you want to use:

$catsArray = array(159, 155, 143, 153, ......);
$series = get_terms( array(
          'taxonomy' => 'ctc_sermon_series',
          'number'  =>  9,
          'offset'  =>  $offset,
          'include' => $catsArray,
          'hide_empty'  => false, 
          'orderby'  => 'include', // <--- 
        ) );

Hope this helps!

Leave a Comment