Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A working sort for taxonomy terms + numeric meta data
<?php
register_taxonomy( 'uh_service_type_taxonomy', array( 'contact_cpt' ), $args );
// add and 'Order' column to Service Type taxonomy terms
add_filter("manage_edit-uh_service_type_taxonomy_columns", "on_manage_edit_uh_service_type_taxonomy_columns");
function on_manage_edit_uh_service_type_taxonomy_columns( $columns ) {
$columns['term_order'] = __('Order');
return $columns;
}
// Output the term's sort order
add_filter( 'manage_uh_service_type_taxonomy_custom_column', 'on_manage_uh_service_type_taxonomy_custom_column', 10, 3);
function on_manage_uh_service_type_taxonomy_custom_column($out, $column_name, $term_id) {
switch ($column_name) {
case 'term_order':
$out = get_field('taxonomy_term_order', get_term($term_id));
break;
default:
break;
}
return $out;
}
add_filter( 'manage_edit-uh_service_type_taxonomy_sortable_columns', 'uh_service_type_taxonomy__sortable' );
function uh_service_type_taxonomy__sortable( $columns ) {
$columns['term_order'] = 'term_order';
return $columns;
}
// Finally. A working sort for taxonomy terms + numeric meta data
add_filter('pre_get_terms', 'uh_service_type_taxonomy__orderby');
function uh_service_type_taxonomy__orderby( $term_query ) {
global $pagenow;
if(!is_admin()) {
return $term_query;
}
// WP_Term_Query does not define a get() or a set() method so the query_vars member must
// be manipulated directly
if(is_admin() && $pagenow == 'edit-tags.php' && $term_query->query_vars['taxonomy'][0] == 'uh_service_type_taxonomy' && (!isset($_GET['orderby']) || $_GET['orderby'] == 'term_order')) {
// set orderby to the named clause in the meta_query
$term_query->query_vars['orderby'] = 'order_clause';
$term_query->query_vars['order'] = isset($_GET['order']) ? $_GET['order'] : "DESC";
// the OR relation and the NOT EXISTS clause allow for terms without a meta_value at all
$args = array('relation' => 'OR',
'order_clause' => array(
'key' => 'taxonomy_term_order',
'type' => 'NUMERIC'
),
array(
'key' => 'taxonomy_term_order',
'compare' => 'NOT EXISTS'
)
);
$term_query->meta_query = new WP_Meta_Query( $args );
}
return $term_query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment