How to Add Custom Meta Fields to Custom Taxonomies in WordPress

53

By default WordPress taxonomies (categories, tags, etc) have the fields name, slug, parent, and description. Recently while working on a client’s project, we found a need to add custom meta fields to custom taxonomies. We needed a way to add custom text on each taxonomy archive page. One way would be to hard code the text using the conditional statements in our taxonomy-{name}.php file. That would be a very inefficient way of doing so, and it would give our client no way to modify the text in the future. So we decided to future proof the situation by adding custom meta fields to custom taxonomies. In this article, we will show you how to add additional custom meta fields to custom taxonomies.

Note: This tutorial is for designers and developers.

While searching for an efficient method, we came across Pippin’s tutorial that shows you how to do this. While his tutorial was great, it required us to write a lot of code. We decided to search a little bit further to see if someone has created an easier way to do this. Perhaps a plugin or a class. Thankfully, we found a solution by Ohad Raz on Github. After going through the same issue, he decided to write a class to make it easy for everyone else (got to love the WordPress community). Thanks Ohad.

In our case, we decided to add this functionality as a plugin rather than in a theme. You can choose the method you like. For the sake of this tutorial, we will go the plugin route.

First thing you need to do is download the Tax-Meta-Class from Github. Create a new folder and call it “taxonomy-fields”. Save the “Tax-meta-class” folder inside that folder.

The zip comes with a file called class-usage-demo.php. Just rename that file, and call it taxonomy-fields.php

Ohad did a great job in documenting the file, so it is pretty self-explanatory. He has examples of all type of fields you can add (text field, textarea, checkbox, select, radio, date, time, color picker, file upload, etc). You don’t have to use all the fields. Simply get rid of the ones you don’t want.

Once you are done adding the fields, upload the taxonomy-fields folder in your plugins folder. Activate the plugin, and add data in your fields.

Now, you are ready to display these additional fields in your taxonomy template. Open your taxonomy template. This would be something like taxonomy-{taxonomy-name}.php file. In there, you can simply add the following:

  <?php     //Get the correct taxonomy ID by slug  $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );    //Get Taxonomy Meta  $saved_data = get_tax_meta($term->term_id,'text_field_id');  echo $saved_data;     ?>  

That’s it. These classes make it really easy and improve your workflow. We hope that this tutorial has helped you in adding custom meta fields to custom taxonomies.

Social Media Auto Publish Powered By : XYZScripts.com