the_tags() : display the tags by the order they are typed in in the backend, not alphabetically

Follow the White Rabbit:

  1. the_tags()
  2. get_the_tag_list()
  3. get_the_term_list()
  4. get_the_terms()
  5. wp_get_object_terms()

If you look through that last function, you should see this:

$defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');

You should have alphabetical order by default. And no, there are no filters I see that would allow you to directly alter the query, but there are several filters along that rabbit hole. The wp_get_object_terms filter looks like a good one to me.

// you will probably need to run this once to reset the cache
// wp_cache_flush();

function id_ordered_tags_wpse_144703($terms, $object_ids, $taxonomies, $args) {

  $taxonomies = explode(',',$taxonomies); // quoted and comma seperated string

  if (1 < count($taxonomies) && !in_array("'post_tag'",$taxonomies)) return $terms;

  $sorted = array();
  foreach ($terms as $term) {
    $sorted[$term->term_id] = $term;
  }

  ksort($sorted);

  return $sorted;
}
add_filter('wp_get_object_terms','id_ordered_tags_wpse_144703',10,4);

// test it
the_tags();

Where you add that code depends on context. In function.php would work but would work but would be restricted only to the theme you add the code to, which I am guessing is correct in this case. Don’t include the the_tags() line. That is just for testing.

A plugin file or mu-plugin file would allow the filter to work for any theme. I doubt that is the intent, and it strikes me a bit unfriendly anyway as it. Again, don’t include the the_tags() line.

You can actually add the code exactly as written in the spot you want to use the_tags(), though that is a messy way to do it.

The code hooks into WordPress Core functions. It will run whenever the wp_get_object_terms filter runs. You don’t have to do anything special besides add the filter callback to the queue, which you do with add_filter.

You can get more control over when the filter runs by adding it when you need it and removing it afterwards:

add_filter('wp_get_object_terms','id_ordered_tags_wpse_144703',10,4);
// test it
the_tags();
remove_filter('wp_get_object_terms','id_ordered_tags_wpse_144703',10);

Leave a Comment