Created
January 23, 2017 14:29
-
-
Save faffyman/c001d63960e3d90d33887469698b9778 to your computer and use it in GitHub Desktop.
Wordpress - Sort Admin Table Column by Taxonomy
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
// functions.php | |
/** | |
* Snippet to create allow a custom admin column to be sortable when it uses Taxonomy terms | |
**/ | |
if(!function_exists('sz_sort_POSTNAME_by_COLUMN-NAME')){ | |
function sz_sort_POSTNAME_by_COLUMN-NAME($clauses, $wp_query){ | |
global $wpdb; | |
if(isset($wp_query->query['orderby']) && $wp_query->query['orderby'] == 'YOUR ORDERBY FIELD'){ | |
$clauses['join'] .= <<<SQL | |
LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id | |
LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id) | |
LEFT OUTER JOIN {$wpdb->terms} USING (term_id) | |
SQL; | |
$clauses['where'] .= "AND (taxonomy = 'YOUR-TAXONOMY' OR taxonomy IS NULL)"; | |
$clauses['groupby'] = "object_id"; | |
$clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC)"; | |
if(strtoupper($wp_query->get('order')) == 'ASC'){ | |
$clauses['orderby'] .= 'ASC'; | |
} else{ | |
$clauses['orderby'] .= 'DESC'; | |
} | |
} | |
return $clauses; | |
} | |
add_filter('posts_clauses', 'sz_sort_POSTNAME_by_COLUMN-NAME', 10, 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment