The get_terms_orderby WordPress PHP filter allows you to modify the ORDERBY clause of a terms query in WordPress.
Usage
add_filter('get_terms_orderby', 'your_custom_function', 10, 3); function your_custom_function($orderby, $args, $taxonomies) { // your custom code here return $orderby; }
Parameters
- $orderby (string): The ORDERBY clause of the terms query.
- $args (array): An array of term query arguments.
- $taxonomies (string[]): An array of taxonomy names.
More information
See WordPress Developer Resources: get_terms_orderby
Examples
Order terms by ID descending
To order terms by their ID in descending order:
add_filter('get_terms_orderby', 'order_terms_by_id_desc', 10, 3); function order_terms_by_id_desc($orderby, $args, $taxonomies) { $orderby = 't.term_id DESC'; return $orderby; }
Order terms alphabetically by slug
To order terms alphabetically by their slug:
add_filter('get_terms_orderby', 'order_terms_by_slug', 10, 3); function order_terms_by_slug($orderby, $args, $taxonomies) { $orderby = 't.slug ASC'; return $orderby; }
Order terms by custom meta key
To order terms by a custom meta key:
add_filter('get_terms_orderby', 'order_terms_by_custom_meta_key', 10, 3); function order_terms_by_custom_meta_key($orderby, $args, $taxonomies) { $orderby = "meta_value ASC, t.name ASC"; return $orderby; }
Order terms by custom meta key and taxonomy
To order terms by a custom meta key for a specific taxonomy:
add_filter('get_terms_orderby', 'order_terms_by_custom_meta_key_and_taxonomy', 10, 3); function order_terms_by_custom_meta_key_and_taxonomy($orderby, $args, $taxonomies) { if (in_array('your_taxonomy', $taxonomies)) { $orderby = "meta_value ASC, t.name ASC"; } return $orderby; }
Order terms randomly
To order terms randomly:
add_filter('get_terms_orderby', 'order_terms_randomly', 10, 3); function order_terms_randomly($orderby, $args, $taxonomies) { $orderby = 'RAND()'; return $orderby; }