T
T
t00rt2018-02-08 16:39:20
WordPress
t00rt, 2018-02-08 16:39:20

How to get term objects in the order they occur in each other?

There is a record included in several terms.
Get all terms with get_the_terms( get_the_ID(), 'taxonomy' );
The response is an array like this:

Array
(
    [0] => WP_Term Object
        (
            [term_id] => 24
            [name] => Подкатегория
            [slug] => sub_term
            [term_group] => 0
            [term_taxonomy_id] => 24
            [taxonomy] => catalogs
            [description] => Подкатегория
            [parent] => 19
            [count] => 5
            [filter] => raw
        )

    [1] => WP_Term Object
        (
            [term_id] => 19
            [name] => Тест категория2
            [slug] => test_in_term2
            [term_group] => 0
            [term_taxonomy_id] => 19
            [taxonomy] => catalogs
            [description] => Тест категория2
            [parent] => 108
            [count] => 5
            [filter] => raw
        )

    [2] => WP_Term Object
        (
            [term_id] => 13
            [name] => Тестовая
            [slug] => test_term
            [term_group] => 0
            [term_taxonomy_id] => 13
            [taxonomy] => catalogs
            [description] => Тестовая категория
            [parent] => 0
            [count] => 5
            [filter] => raw
        )

    [3] => WP_Term Object
        (
            [term_id] => 108
            [name] => УберТест
            [slug] => ubertest
            [term_group] => 0
            [term_taxonomy_id] => 109
            [taxonomy] => catalogs
            [description] => УберТест
            [parent] => 13
            [count] => 5
            [filter] => raw
        )

)

The point is to sort the array so that the term objects in it go in the order of their nesting into each other, i.e. for example, an object with term_id=108 must be between term_id=13 and term_id=19, because 13 is the parent of 108, and 108 is the parent of 19.
In principle, the problem is to get the nearest term in which the record is nested. and from it you can build everything up.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question