Last active
August 29, 2015 14:03
-
-
Save michaeldozark/0cd846f9371684dc2e01 to your computer and use it in GitHub Desktop.
Filters get terms in the order the term_ids are listed in the `include` parameter of get_terms.
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 | |
add_filter( 'get_terms_args', 'slimline_get_terms_args', 0 ); // allow extra filtering of terms arguments | |
/** | |
* slimline_get_terms_args filter | |
* | |
* Adds additional filtering to get_terms as needed. | |
* | |
* @param array $args An array of arguments passed from the get_terms() function | |
* @return array $args Arguments after filtering. | |
* @since 0.2.0 | |
*/ | |
function slimline_get_terms_args( $args ) { | |
if ( 'term__in' === $args[ 'orderby' ] ) { | |
add_filter( 'get_terms_orderby', 'slimline_order_terms_by_field', 10, 2 ); // adds SQL FIELD ordering to get_terms | |
} // if ( 'term__in' === $args[ 'orderby' ] ) | |
return $args; | |
} | |
/** | |
* slimline_custom_order_terms filter | |
* | |
* Orders terms by the order the ids were entered into the args list | |
* | |
* @param string $orderby ORDER BY clause of the terms query. | |
* @param array $args An array of terms query arguments. | |
* @return string $orderby FIELD function if include IDs were set or 'name' if not | |
*/ | |
function slimline_custom_order_terms( $orderby, $args ) { | |
/** | |
* check to see if include IDs have been set | |
* | |
* ORDER BY FIELD() will only work if the "include" parameter is set. If not, change the orderby parameter to "name" | |
* and continue. | |
*/ | |
if ( isset( $args[ 'include' ] ) && ! empty( $args[ 'include' ] ) ) { | |
// make sure we use a comma-separated list in our SQL statement | |
$terms = ( is_array( $args[ 'include' ] ) ? join( ',', $args[ 'include' ] ) : $args[ 'include' ] ); | |
/** | |
* WordPress joins the wp_terms (t) and wp_term_taxonomy (tt) tables on term_id when using get_terms. | |
* We are using SQL FIELD to order the term_ids based on the order they are entered into the include parameter. | |
*/ | |
$orderby = 'FIELD(tt.term_id,' . $terms . ')'; | |
} else { // if ( isset( $args[ 'include' ] ) && ! empty( $args[ 'include' ] ) ) | |
$orderby = 'name'; | |
} // if ( isset( $args[ 'include' ] ) && ! empty( $args[ 'include' ] ) ) | |
remove_filter( 'get_terms_orderby', 'slimline_custom_order_terms', 10 ); // don't let this filter alter other queries on the same page | |
return $orderby; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment