Return multiples taxonomies with wp_get_object_terms
-
22-04-2021 - |
Frage
I have a loop to display the posts of my Custom Post Type 'workshop'. Inside the loop I display the related terms of two taxonomies 'area' and 'group' using wp_get_object_terms()
.
It works fine. However I'm struggling to control the order of the taxonomies when displayed. It should always be in first 'area' then 'group'.
The code to display the related taxonomies:
<?php $workshop_terms = wp_get_object_terms( $post->ID, array( 'area', 'group' ) );
if ( ! empty( $workshop_terms ) ) {
if ( ! is_wp_error( $workshop_terms ) ) {
foreach( $workshop_terms as $term ) {
echo esc_html( $term->name );
}
}
} ?>
Thank you.
Lösung
wp_get_object_terms()
accepts a third parameter which is an array of arguments passed to WP_Term_Query::get_terms
which runs the actual SQL queries for the specific term request, and one of the arguments is named orderby
which accepts term fields like name
and taxonomy
.
So you can use that 3rd parameter and set the orderby
to taxonomy
(and order
to ASC
) like so:
$workshop_terms = wp_get_object_terms( $post->ID, array( 'area', 'group' ), array(
'orderby' => 'taxonomy',
'order' => 'ASC',
) );
Or the other way, is of course, call wp_get_object_terms()
once for each of the taxonomies... ✌🙂