admin管理员组

文章数量:1303412

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.

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.

Share Improve this question asked Feb 15, 2021 at 10:31 Mathieu PréaudMathieu Préaud 2035 silver badges18 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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... ✌

本文标签: custom post typesReturn multiples taxonomies with wpgetobjectterms