[wp-trac] [WordPress Trac] #40335: using 'pre_get_terms' is confusing when it comes to ordering by meta

WordPress Trac noreply at wordpress.org
Sun Apr 2 09:41:05 UTC 2017

#40335: using 'pre_get_terms' is confusing when it comes to ordering by meta
 Reporter:  wujek_bogdan  |      Owner:
     Type:  enhancement   |     Status:  new
 Priority:  normal        |  Milestone:  Awaiting Review
Component:  Query         |    Version:  4.7.3
 Severity:  normal        |   Keywords:
  Focuses:                |
 There's a  `pre_get_terms` hook. One might think that it works in the same
 way how `pre_get_posts` works, but it doesn't.

 I wanted to order terms by a meta field, so I did something like this:

 add_action('pre_get_terms', function (\WP_Term_Query $query) {


     $queryVars = $query->query_vars;

     $args = [
         'meta_key' => 'my_meta_key',
         'orderby' => 'meta_value',
         'order' => 'ASC',

     $query->query_vars = array_merge($queryVars, $args);

 And for `pre_get_posts` this technique would work. But with
 `pre_get_terms` it's different.  Digging into `WP_Term_Query` class code I
 found that this code would cause `parse_orderby()` method to set the
 `$maybe_orderby_meta` variable to `true`. But it doesn't mean that terms
 will be sorted by a meta field. It only means that terms '''maybe''' will
 be sorted by meta.

 There's an another filter required. At the end of the `parse_orderby()`
 method there's an another filter applied: `get_terms_orderby`.

 So in order to sort terms by meta field there's one more thing required.
 Something like:

 add_filter('get_terms_orderby', function ($orderby, $args) {

         return $orderby;

     return 'meta_value';
 }, 10, 2);

 This is unintuitive and confusing, and what's the most important: it's not
 documented. The documentation should be very clear about it. Because of
 the filter name, that's very similar to the `pre_get_posts` filter name,
 users might expect it to work in the same way.  It might be even
 considered as a bug. So I'll mark it as a bug, because from the user's
 perspective this is how it looks like.

Ticket URL: <https://core.trac.wordpress.org/ticket/40335>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform

More information about the wp-trac mailing list