Add Fields to Taxonomy Terms
https://rudrastyh.com/wordpress/add-custom-fields-to-taxonomy-terms.html
Last updated
Was this helpful?
https://rudrastyh.com/wordpress/add-custom-fields-to-taxonomy-terms.html
Last updated
Was this helpful?
Today WordPress has meta field support for nearly everything – post types, users, comments, blogs within a multisite network and yes, taxonomy terms.
To add the fields on the “Add new” screen we are going to use an action hook {Taxonomy}_add_form_fields
and all we have to do is to echo the fields.
I decided to add a field to post_tag
taxonomy, so my action hook is post_tag_add_form_fields
. But you can use any custom taxonomy name here.
Taxonomy name as $taxonomy
variable is available inside the function.
Do not forget to wrap the field inside a div
with form-field
class.
Very similar to the previous part of the tutorial, the main difference is that we have to populate the field in case the metadata is presented.
Let’s begin with an action hook {Taxonomy}_edit_form_fields
. For post_tag
taxonomy it is going to be post_tag_edit_form_fields
, for your custom taxonomy it could be misha_taxonomy_edit_form_fields
.
Function has two parameters: $term
– which is a currently edited term object, $taxonomy
– taxonomy name.
We’re using get_term_meta()
function here to get the term meta data.
Do not forget to escape the data you get from the database.
The last step is to save our fields values into the database. Guess what – we also have two action hooks for that – created_{Taxonomy}
and edited_{Taxonomy}
. Luckily we can connect the same callback function to both of them.
That’s it.
Not so difficult, but below I am going to show you even more simple way to create taxonomy term fields!
Sometimes it takes to long to create fields from scratch. So I decided to create a plugin which allows to simplify the process and to save a lot of time.
So, if you have my plugin installed on your website, just insert the below code to your current theme functions.php
and a text field will appear on your add/edit term pages.
Screenshots of what we are going to create:We are going to create a simple text field and this is how it is going to look on add new term pages.This is how our field is going to look on edit term pages.
Result:We can add fields to the Add New tag page with post_tag_add_form_fields
action hook.
And we have it:We can add fields to the Edit Tag page with post_tag_edit_form_fields
action hook.