1

I'm looking for the simplest method of preserving the term order in a non-hierarchical taxonomy on a per-post basis. I was able to achieve this previously using the following code in register_taxonomy coupled with a get_the_terms filter.

'sort' => true,
'args' => array( 'orderby' => 'term_order' ),

As of WordPress 4.7 this no longer seems to work, and the sort argument no longer appears to do anything at all.

All I need is to be able to enter "bananas, apples, pears" in a "Fruits" taxonomy field on the Add/Edit Post page and have that term order preserved after I press "Publish" or "Update." The next post could list "pears, bananas, apples". Right now even if I can get that original order to stick after the initial Publish, because it alphabetizes it on the admin page any original order is lost on subsequent publishes/updates to the Post.

Is there a filter I can apply to prevent the values from being reordered alphabetically, or does the actual term order need to be saved as separate metadata?

For reference, the code I had originally used (which I've seen reused here to answer similar questions) is at the bottom of this page: https://core.trac.wordpress.org/ticket/5857 and term_order is discussed in further detail here: https://core.trac.wordpress.org/ticket/9547

1 Answer 1

1

I encountered a similar issue and this is how I solved it. Note that I put in Fruits as the taxonomy name based on your example. It's important that this name matches the taxonomy name exactly. Often taxonomy names are singular, i.e. fruit

function wp4382_filter_terms_order( $orderby, $query_vars, $taxonomies ) {
    if ( ! empty( $query_vars['object_ids'] )
        && ! empty( $taxonomies[0] )
        && ( 1 === count( $taxonomies ) )
        && 'Fruits' === $taxonomies[0] )
    {
        $orderby = 'tr.term_order';
    }
    return $orderby;
}

add_filter( 'get_terms_orderby', 'wp4382_filter_terms_order', 10, 3 );
1
  • Linnea, that is EXACTLY the code I was looking for. Thank you so much for your answer. It seems to work regardless of the settings I mentioned above in register_taxonomy. I used this coupled with the get_the_terms filter I had been using originally (first link above) so the code you provided was all I needed to get this working again.
    – M. Doucet
    Commented Dec 18, 2016 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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