get_categories order by meta key issue?

I’m trying to search for a way to order categories by meta value. From what I read, it seems like I can use:

get_categories(‘child_of=92&hide_empty=false&orderby=meta_value&meta_key=date&order=ASC’);

Read More

However, this does not work at all, the categories are still not in the order I want. I wonder how I can:

  1. correct this to make it work
  2. print out the sql to see what is really going on inside?

Thank you very much in advance.

Related posts

Leave a Reply

2 comments

  1. First of all, I must mention that I’m using the module custom category fields, and second of all I’m a complete WP newbie

    Anyhow, after learning that this cannot be done by default, I looked into the get_categories functions and finally came up with a solution

    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);
    

    (The code above can be put into the theme functions.php file)

    then the code to get categories is:

    get_categories('child_of=92&hide_empty=false&orderby=category_custom_field&category_custom_field=date&order=DESC');
    

    Any correction is greatly appreciated!

  2. You can also give the get_categories new meta and sort using usort.

    $subcategories = get_categories();
    
    foreach ($subcategories as $subcategory) {
    $subcategory->your_meta_key = your_meta_value;
    }
    
    foreach ($subcategories as $subcategory) {
    blah blah blah
    }
    
    function my_cmp($a, $b) {
    if ($a->ordering == $b->ordering) {
    return 0;
    }
    return ($a->ordering < $b->ordering) ? -1 : 1;
    }
    
    
    usort($subcategories, "my_cmp");