Forked from ontiuk/wordpress_terms_clauses_sorting.txt
Created
October 17, 2020 19:16
-
-
Save ValeriiVasyliev/544be55b37bc79a462a49af63bf282d7 to your computer and use it in GitHub Desktop.
WordPress: Taxonomy Meta Sorting With Terms_Clauses Filter
This file contains hidden or 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
add_filter( 'terms_clauses', 'filter_terms_clauses', 10, 3 ); | |
/** | |
* Filter WP_Term_Query meta query | |
* | |
* @param object $query WP_Term_Query | |
* @return object | |
*/ | |
function filter_terms_clauses( $pieces, $taxonomies, $args ) { | |
global $pagenow, $wpdb; | |
// Require ordering | |
$orderby = ( isset( $_GET['orderby'] ) ) ? trim( sanitize_text_field( $_GET['orderby'] ) ) : ''; | |
if ( empty( $orderby ) ) { return $pieces; } | |
// set taxonomy | |
$taxonomy = $taxonomies[0]; | |
// only if current taxnomy or edit page in admin | |
if ( !is_admin() || $pagenow !== 'edit-tags.php' || !in_array( $taxonomy, [ 'my-taxonomy-name' ] ) ) { return $pieces; } | |
// and ordering matches | |
if ( $orderby === 'my-taxonomy-meta-field-name' ) { | |
$pieces['join'] .= ' INNER JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id '; | |
$pieces['where'] .= ' AND tm.meta_key = "my-taxonomy-meta-field-name" '; | |
$pieces['orderby'] = ' ORDER BY tm.meta_value '; | |
} | |
return $pieces; | |
} | |
// Change taxonomy and taxonomy meta fields as required. Requires taxonomy meta column and sortable column filters to be active. | |
// This just ties them together and makes the taxonomy meta field column sortable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment