0

When using get_the_terms to retrieve terms within a taxonomy for a custom post type you can't pass arguments, like so:

function custom_cat_function() {
    global $post;
    $args = array(
      'orderby'    => 'ID',
      'order'      => 'ASC',
    );
    $terms = get_the_terms($post->id, 'category', $args);
    $count = count( $terms );
    if ( $count > 0 ) {
        foreach ( $terms as $term ) {
            echo '<li>' . $term->name . '</li>';
        }
    }
}

all documentation points to other functions like get_terms, but get_terms retrieves ALL terms within a taxonomy, not just the terms for that single post (within a loop).

How do you properly pass arguments like the example above (I'm aware the example above is not right, but I wrote it as a baseline example of what needs to be achieved)

2

get_the_terms uses wp_get_object_terms with defaults, which is orderby name ascending. You can use wp_get_object_terms directly if you want to set arguments differently.

$args = array(
    'orderby' => 'term_id'
);
$terms = wp_get_object_terms( get_the_ID(), 'category', $args );
  • was looking at using this but read in documentation "It should be noted that the results from wp_get_object_terms are not cached which will result in a db call everytime this function is called. For performance, functions like get_the_terms() (which the results of has been cached), should be used." – bmlbml Mar 30 '16 at 23:37
  • 1
    I think you have a choice between ordering terms yourself in php with get_the_terms or no cache and ordered the way you want via wp_get_object_terms – Milo Mar 31 '16 at 4:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.