This can be easily done with your own custom function. What you want to do here is, get your object from get_terms()
which will hold your term objects, and through a foreach
loop, remove the desired key/value pair and stick that to the end of the array.
Now, lets put that into code
This needs at least PHP 5.4
function get_term_to_end( $taxonomy = '', $args = [] )
{
/*
* Return get_terms as is if our new argument term_to_end is not set or empty
*/
if ( !isset( $args['term_to_end'] ) || empty( $args['term_to_end'] ) )
return get_terms( $taxonomy, $args );
/*
* If term_to_end is set and has a value, continue to process
*/
$terms = get_terms( $taxonomy, $args );
/*
* Return $terms if a wp error is returned or if $terms is empty
*/
if ( is_wp_error( $terms ) || empty( $terms ) )
return $terms;
/*
* We have came this far, now we can finish this off
*/
foreach ( $terms as $term ) {
/*
* Check the term ids against our new argument term_to_end
*/
if ( $term->term_id == $args['term_to_end'] ) {
$end[] = $term;
} else {
$terms_array[] = $term;
}
}
/*
* Merge the two arrays together, adding the term_to_end right at the back
*/
$terms = array_merge( $terms_array, $end );
/*
* For uniformaty, type cast the resultant array to an object
*/
return (object) $terms;
}
Example use case:
Move term with id 15 belonging to the taxonomy mytax
to the back of the term array. Keep the default odering by name
$terms = get_term_to_end( 'mytax', ['term_to_end' => 15] );
Or
$args = [
'term_to_end' => 15
];
$terms = get_term_to_end( 'mytax, $args );
FEW NOTES ON THE ABOVE
The code above is all untested and might be buggy. I have written this on a tablet.
For older versions (pre PHP 5.4), use the first code block and simply change the new array syntax (
[]
) to the old syntax (array()
)The new parameter,
term_to_end
uses the term to move to the end term's ID. You can modify this to work with either the term name or term slug, whatever suites your need. You can also modify this to work with all of these valuesThe new function uses the exact same parameters as
get_terms()
. The only extra addition is theterm_to_end
parameterAs
get_terms
, the new function returns aWP_Error
object if a taxonomy does not exists and also returns an ampty array if no terms are found. Remember to check for these occurances in the same way you would withget_terms
If the
term_to_end
parameter is set, thefields
parameter cannot be set to anything else thanall
(which is the default). Any other value will break the function. You can modify this very easily to work properly by building in some conditional checks and changing theforeach
in the first code blockYou can very easily change the function to move a selected term to the front if needed. You can also adjust the function to accept multiple terms to move
For any other info regarding the use of this function, please see
get_terms
EDIT
This code in now tested and working as expected. The PHP5.5 version was removed as it has an issue with array_search