pre_get_posts
is an action hook used for modifying the arguments passed to the WP_Query
class, and if you’re filtering the posts in the list table at wp-admin/edit.php
, then yes, you would use that hook.
However, since you’re filtering the terms in the list table at wp-admin/edit-tags.php
, then the hook that you should have used is pre_get_terms
, which can be used to modify the arguments passed to the WP_Term_Query
class.
- That class is used by
get_terms()
which is used by the class which renders the terms list table.
But then, I don’t know for sure why ( maybe it’s a bug in WordPress core? 🤔 ), but when sorting by meta value, i.e. when orderby
is meta_value_num
, meta_value
, or a key in a meta_query
array, it seems we need to use the parse_term_query
hook instead, which runs before pre_get_terms
.
And here’s an example you can try, and note that unlike WP_Query
, WP_Term_Query
doesn’t have a get()
or set()
method, hence I directly accessed/modified the query_vars
property:
add_action( 'parse_term_query', 'weight_column_orderby' );
function weight_column_orderby( WP_Term_Query $query ) {
// Check whether we are at wp-admin/edit-tags.php?taxonomy=weight-class
if ( ! is_admin() ||
! function_exists( 'get_current_screen' ) ||
'edit-weight-class' !== get_current_screen()->id
) {
return;
}
$taxonomies = (array) $query->query_vars['taxonomy'];
// Modify the args, if `weight` is the `orderby` value, and that the query
// is for your custom `weight-class` taxonomy.
if ( 'weight' === $query->query_vars['orderby'] &&
in_array( 'weight-class', $taxonomies, true )
) {
$query->query_vars['meta_key'] = 'weight';
$query->query_vars['orderby'] = 'meta_value_num';
}
}