Sort WordPress Terms with term_meta Custom Fields

In an earlier article, I recommended the WordPress sorting plugin Anything Order. It is convenient, but in some situations it can conflict with other plugins. Before WordPress 4.4, taxonomy term ordering was limited to built-in fields such as id, term_id, name, and slug. WordPress 4.4 introduced support for taxonomy custom fields through term_meta, and that gives us a clean way to sort terms using our own custom numeric value.

Add an input field for the term’s custom sort value

First, we need to add a custom field to the taxonomy term edit form. After doing that, a sort-order field appears when we edit the category in the dashboard. We can enter numbers from small to large according to the sorting order we want.

Term meta field used for taxonomy ordering
/**
 * Taxonomy term order field
 *
 * @param        Term Object $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( '排序' ); ?></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 taxonomy terms by the custom field when retrieving them

Once the term meta exists, front-end term queries become simple. Just pass a meta_key and set the ordering method to meta_value_num when calling get_terms().

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

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

If needed, you can also display the sort number in the admin category list with functions such as manage_category_custom_column so editors can see the ordering more clearly in the back end.

Related Posts

Leave a Reply

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