A recent project required a custom, sortable column for a taxonomy which contained a custom field. I found plenty of tutorials on how to make a custom sortable column in the WordPress edit screen, but sadly their scopes were all confined to the post edit screen. The code from those tutorials got me 90% of the way there, but they did not provide working examples of sortable custom columns on the taxonomy or post_tag edit screen.
Most tutorials I found relied on the
pre_get_posts action hook to modify the edit screen’s query and sort its results by
meta_key. Unfortunately this poses two issues: (1)
pre_get_posts is not an action hook available to us when querying taxonomy terms into the admin grid/table on
wp-admin/edit-tags.php?taxonomy=post_tag; and (2) in my case, my
wp_terms table does not have native metadata and the custom field I wanted to search by was located in another table. I understand that #2 may be available in future versions of WordPress and custom fields plugins, but for purposes of this post I assume your taxonomy has metadata stored in a table outside the native
wp_terms table (mine is stored in
I poked around in the WordPress taxonomy API (
wp-includes/taxonomy.php in WP 4.3.1) and discovered that the query is set on line 2004 and above it we have access to several filters which allow us to modify the query. #1 solved.
My custom taxonomy is called
issue and the custom field is a required date picker called
issue-date (created using ACF PRO). Using phpMyAdmin I ran a quick search in my database for
issue-date to figure out where the metadata was being stored:
So we need to join the
wp_options table to our query…
option_name intersecting with our
term_id and sorted by
option_value to solve #2.
IMPORTANT: make sure if you’re using a date picker field like I was that you set its return format to
Here’s how I ended up doing it:
Step 1: Create the new column itself, it will be empty initially
Step 2: Populate the new column
Step 3: Make the new column sortable
Step 4: Define the custom sorting (where the magic happens)
This worked right out of the gate for me. Notice that my two ternary expressions (lines 10 & 11 in step 4) ensure that Issues will be sorted descending by date (newest first) when an admin first arrives at the Issue edit screen until they specify different sorting criteria. That is what my client really wanted so I set it up as the default.
Enjoy your new custom, sortable taxonomy columns!
Is this working in latest wp? I added all snippets in functions.php. But couldnt get the taxonomy date column.
Works for me on the latest WP. Could be an issue with your code or a plugin, but I have no way of knowing without you posting your code and telling me the actual result. Are you just not seeing the new column at all?