Sorting WordPress Terms with term_meta

I previously recommended the Anything Order plugin for sorting WordPress taxonomy terms. It is convenient, but plugins can sometimes conflict with other parts of a project. Before WordPress 4.4, term ordering was mostly limited to built-in fields such as id, term_id, name, and slug. Since WordPress 4.4 introduced support for term_meta, we can store a custom ordering value and use that value directly for sorting.

Add a Custom Order Field to the Term Edit Screen

First, add a custom field to the category edit form. After this, when you edit a category, you will see an extra order input. If you want ascending order, simply enter smaller and larger numbers according to the order you need.

term-meta-order
/**
 * Category term order field
 *
 * @param Term   $term
 * @param string $taxonomy
 */
add_action( 'category_edit_form_fields', 'term_order_field', 10, 2 );
function term_order_field( $term, $taxonomy ) {
   ?>

   <table class="form-table">
      <tbody>
      <tr class="form-field">
         <th scope="row" valign="top">
            <label for="meta-order"><?php _e( 'Order' ); ?></label>
         </th>
         <td>
            <input type="text" name="_term_order" size="3" style="width:10%;" value="<?= get_term_meta( $term->term_id, '_term_order', true ); ?>"/>
         </td>
      </tr>
      </tbody>
   </table>

   <?php
}

/**
 * Save the order value
 *
 * @param int $term_id
 */
add_action( 'edited_category', 'save_term_order' );
function save_term_order( $term_id ) {
   update_term_meta( $term_id, '_term_order', $_POST[ '_term_order' ] );
}

Sort Terms by the Custom Field

Once the custom field is saved, ordering terms on the front end becomes very simple. Pass a meta_key and set orderby to meta_value_num when calling get_terms().

$args = [
   'meta_key' => '_term_order',
   'orderby'  => 'meta_value_num',
];

$terms = get_terms( 'category', $args );

If you want, you can also display the order number in the category list in the WordPress dashboard so the current sort order is easier to see at a glance.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *