[wp-hackers] ordering the cats in a particular order

Jeremy Clarke jer at simianuprising.com
Mon Apr 16 22:43:22 UTC 2012


On Mon, Apr 16, 2012 at 11:17 AM, Alex Rayan <alexrayan69 at gmail.com> wrote:

>
> As of now, there is no direct filter on wp_terms_checklist. And replicating
> the same code might not be the best idea.
>
>
I needed to change the order of categories in the metabox to re-alpha-sort
them because for some reason my Arabic site's categories were not in Arabic
"alphabetical" order. The closest thing I found to a filter for the
checklist was to use the *get_terms* filter and perform my manipulations
there.

Obviously this could have unintended effects in other parts of the site,
but at the same time it might have quite desirable effects in those same
places. It's likely that if you want a certain order in wp-admin, you also
want it when displaying lists of categories anywhere else.

The important thing is to be careful to only filter it at times when
get_terms() is already using the kind of data that the checkbox uses and
that your filtering function assumes is there. Specifically *$args['fields']
= all* and *$args['orderby']  = name*. Your filtering function that works
on the list of objects will completely destroy an array of IDs! (learned
that the hard way)

Here's the code I ended up with, which seems to work well for me.

function gv_filter_get_terms($terms, $taxonomies, $args) {

/**
 * Only run this filter if we're fetching the default fields 'all'
 * avoids trying to object-filter lists of ids or names.
 */
 if ('all' != $args['fields'])
return $terms;
 /**
 * Only sort if 'orderby' is 'name'. It's the default so it will still be
'name' if fields='ids'
 */
if ( 'name' == $args['orderby'] )
 usort( $terms, '_usort_terms_by_name' ); // usort func is part of wp core

 reset ( $terms );
 return $terms;
}
add_filter('get_terms', 'gv_filter_get_terms', 10, 3);

Obviously you'll want to replace the *usort()* line with whatever
manipulations you want to do.

IIRC get_terms runs itself recursively when you have a hierarchical
taxonomy, so this will run several times, once for top-level parents, then
once for each set of children/grandchildren. In my case this wasn't an
issue because I just wanted to enforce alpha-sorting within each set of
categories, but it might make your life more complicated if you decide to
go this route.


-- 
Jeremy Clarke • jeremyclarke.org
Code and Design • globalvoicesonline.org


More information about the wp-hackers mailing list