Get categories ordered by meta key on WordPress

For our website, we are using WordPress (we used to use Zencart before, but now we switched to WordPress and will only use Zencart for the store section). So for our own purpose we installed a WordPress plugin called Category Custom Fields which can add unlimited custom fields to any cateogry/taxonomy.

The problem with the plugin though, was that there was no way we could order the categories by those extra custom fields (this is true as of the date this article is written).


This was supposed to work, but it did not. I searched high and low without a solution, then finally after reading lots of articles and checking the code I found out that this can be done using WordPress “hooks” without hacking into the core code:

Simply put the code below into your theme’s functions.php file:

function category_custom_field_get_terms_orderby( $orderby, $args ){
    if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
        return 'cv.field_value';
    return $orderby;

function category_custom_field_get_terms_fields( $selects, $args ){
    if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
        $selects[] = 'cv.*';
    return $selects;

function category_custom_field_terms_clauses($pieces, $taxonomies, $args){
    global $wpdb;
    if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
        $pieces['join'] .= " LEFT JOIN $wpdb->prefix" . "ccf_Value cv ON cv.term_id = tt.term_id AND cv.field_name = '".$args['category_custom_field']."'";
    return $pieces;

add_filter('get_terms_orderby', 'category_custom_field_get_terms_orderby',1,2);

add_filter('get_terms_fields', 'category_custom_field_get_terms_fields',1,2);

add_filter('terms_clauses', 'category_custom_field_terms_clauses',1,3);

And now you can get the categories in the order you want using:


I have posted this question on stackoverflow as well (and ended up answering my own question)

Leave a Reply