Order get_terms by term meta

I have a custom taxonomy called prod-cat

I want to order the output in the template by number, so I added a term_meta to the taxonomy like this:

add_action( 'prod-cat_add_form_fields', 'add_feature_group_field', 10, 2 );
function add_feature_group_field($taxonomy) {
    ?>
    <div class="form-field term-order-wrap">
        <label for="term-order">Order</label>
        <input type="text" name="wm-cat-prod-order" />
    </div>
    <?php
}

And then:

add_action( 'created_prod-cat', 'save_feature_meta', 10, 2 );
function save_feature_meta( $term_id, $tt_id ){
    if( isset( $_POST['wm-cat-prod-order'] ) && '' !== $_POST['wm-cat-prod-order'] ){
        add_term_meta( $term_id, 'wm-cat-prod-order', $_POST['wm-cat-prod-order'], true );
    }
}

I have the term_meta working, It’s getting saved. Then in the template I do this:

$args = array(
    'taxonomy'      =>  'categoria-de-productos',
    'orderby'       =>  'wm-cat-prod-order',
    'order'         =>  'ASC',
    'hide_empty'    =>  false,
    'hierarchical'  =>  false,
    'parent'        =>  0,
);

$terms = get_terms( $args );

But I can’t get it to orderby the “wm-cat-prod-order” meta.
Anyone on this?
Thanks

4 s
4

get_terms supports a meta_query which calls a new WP_Meta_Query parameter as you can see here. To query your terms with your desired meta, you could change your function call to something like this:

$args = array(
  'taxonomy' => 'categoria-de-productos',
  'orderby' => 'meta_value_num',
  'order' => 'ASC',
  'hide_empty' => false,
  'hierarchical' => false,
  'parent' => 0,
  'meta_query' => [[
    'key' => 'wm-cat-prod-order',
    'type' => 'NUMERIC',
  ]],
);

$terms = get_terms( $args );

This code is untested and may needs to be changed in your example. But the links should guide you to the solution.

Leave a Comment