Created
December 12, 2017 14:13
-
-
Save Phoenix2k/18aa5e09ebe2e8c259b60b07ea97cc75 to your computer and use it in GitHub Desktop.
WordPress: Custom taxonomy columns with sorting support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This example uses 'main-category' as a custom taxonomy and values | |
* from Carbon Fields for sorting https://carbonfields.net | |
*/ | |
// Add custom column title | |
add_filter( 'manage_edit-main-category_columns', function( $columns ) { | |
$column_position = 2; | |
$before = array_slice( $columns, 0, $column_position, true ); | |
$after = array_slice( $columns, $column_position, count( $columns ), true ); | |
$custom_column = [ | |
'is_public' => __( 'Public', 'your-textdomain' ) | |
]; | |
$columns = array_merge( $before, $custom_column, $after ); | |
return $columns; | |
}, 10, 3 ); | |
// Render custom column content | |
add_filter( 'manage_main-category_custom_column', function( $content, $column_name, $term_id ) { | |
if ( 'is_public' === $column_name ) { | |
$content = carbon_get_term_meta( $term_id, 'crb_is_public' ) ? "\u{2705}" : "\u{1F6D1}"; // ✅ 🛑 | |
} | |
return $content; | |
}, 10, 3 ); | |
// Make custom column sortable | |
add_filter( 'manage_edit-main-category_sortable_columns', function( $sortable ) { | |
$sortable[ 'is_public' ] = 'is_public'; | |
return $sortable; | |
}, 10, 3 ); | |
// Add custom sortable content to taxonomy query | |
add_filter( 'terms_clauses', function( $pieces, $taxonomies, $args ) { | |
global $pagenow, $wpdb; | |
$custom_sort_term = 'is_public'; | |
$custom_taxonomy = 'main-category'; | |
$orderby = ( isset( $_GET[ 'orderby' ] ) ) ? trim( sanitize_text_field( $_GET[ 'orderby' ] ) ) : ''; | |
if ( empty( $orderby ) ) { return $pieces; } | |
$taxonomy = $taxonomies[ 0 ]; | |
if ( ! is_admin() || 'edit-tags.php' !== $pagenow || ! in_array( $taxonomy, [ $custom_taxonomy ] ) ) { | |
return $pieces; | |
} | |
if ( $custom_sort_term === $orderby ) { | |
$pieces[ 'join' ] .= ' INNER JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id '; | |
$pieces[ 'orderby' ] = ' ORDER BY tm.meta_value '; | |
$pieces[ 'where' ] .= ' AND tm.meta_key = "_crb_is_public"'; | |
} | |
return $pieces; | |
}, 10, 3 ); |
Excellent, couldn't find the proper way to solve this anywhere! I removed the where clause and used a left join to return terms without any value for my $custom_sort_term
.
if ($this->field === $orderby) {
$pieces['join'] .= ' LEFT JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id ';
$pieces['orderby'] = ' ORDER BY tm.meta_value ';
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this.