I'm tearing my hair out trying to figure out what's wrong with this code. I've already read and tried every single question on this topic on StackOverflow - I'm hoping someone can spot a small bug and figure it out.
I have a custom post type called "books" with custom taxonomy "book-series". The "book-series" taxonomy has a custom meta value of "series-index-number" associated with it (used to display series in a certain order).
I want to display "series-index-number" as one of the columns on the main taxonomy page and also have it be sortable.
DISPLAYING the values is WORKING.
SORTING by the column is NOT WORKING.
Here's the full code:
UPDATE: I found the solution - use pre_get_terms to add on an action that will attach a meta class the term query. The code below is updated to reflect the working version.
...
// display the series index numbers on the main series list page
add_filter('manage_edit-book-series_columns', 'add_series_index_column' );
add_filter('manage_book-series_custom_column', 'add_series_index_column_content', 10, 3 );
add_filter('manage_edit-book-series_sortable_columns', 'add_series_index_column_sortable' );
add_action( 'pre_get_terms', 'series_orderby' );
// add series index column to series page
function add_series_index_column( $columns ){
$columns['series_index'] = 'Order Number';
return $columns;
}
// add actual series index values to the table
function add_series_index_column_content( $content, $column_name, $term_id ){
if( $column_name !== 'series_index' ){
return $content;
}
$term_id = absint( $term_id );
$display_index = get_term_meta( $term_id, 'series-index-number', true );
if( !empty( $display_index ) ){
$content .= esc_attr( $display_index );
}
return $content;
}
// make series index column sortable
function add_series_index_column_sortable( $sortable ){
$sortable[ 'series_index' ] = 'series_index';
return $sortable;
}
function series_orderby( $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] == 'book-series' && (isset($_GET['orderby']) || $_GET['orderby'] == 'series_index')) {
// 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' => 'series-index-number',
'type' => 'NUMERIC'
),
array(
'key' => 'series-index-number',
'compare' => 'NOT EXISTS'
)
);
$term_query->meta_query = new WP_Meta_Query( $args );
}
return $term_query;
}
...