Creating Custom Content: Taxonomies and Fields

Creating Custom Content: Taxonomies and Fields

Online by J&S Code
19 July 2017 | MySQL PHP WP snippets, code & hacks | 1107 recognitions

Organizing your content is one of the core features of a content-management system like WordPress. As such, it creates what are called “taxonomies” to help you keep your content easy to find for both your and your visitors. Today we’re focused on why and how you make a custom taxonomy.

Average WordPress user may not recognize the term “taxonomy” but they are almost certain to know what “categories” and “tags” are. We’ll start with explaining a bit more about taxonomies, and then we’ll move on to getting detailed about WordPress custom taxonomies — why and how you make them, and a newer extra feature they have.

Creating Custom Content: Taxonomies and Fields

Understanding Taxonomies

If you’re using WordPress as a blog, you’re already using taxonomies—you just may not know them by that name. A taxonomy is simply a system of organizing information. A WordPress taxonomy, specifically, organizes WordPress posts. Your WordPress posts have two taxonomies by which they can be organized: Categories and Tags.

A taxonomy is simply a system of organizing information. A WordPress taxonomy, specifically, organizes WordPress posts.

Tags are considered a flat taxonomy: all tags are equal, and no tags are members of other tags. This makes it great for quick entry of possibly-relevant data, but makes it hard to be organized and disciplined about it. You might think to tag a dog with things like “brown”, “furry”, “soft”, “cuddly”, and “cute”. All of these apply, but they don’t all fit into a single way of thinking about dogs.

In contrast, categories are a hierarchical taxonomy: elements can be nested such that something in your “Five Paragraph Essays” category is automatically also a member of its parent category “Essays.”

Or to come back to dogs, we know our way of understanding all living things as a hierarchical taxonomy. Domestic dogs are often identified as Canis lupis (familiaris). Canis is the genus, lupis is the species. All species lupis are members of the taxonomical category of Canus, but the reverse is not true. Coyotes also belong to the Canus genus, but are not either dogs (or wolves).

All living creatures are put into the taxonomical system of scientific classification. If you learned “kingdom-phylum-class-order-family-genus-species” in a biology class ever, that’s what we’re talking about here. The scientific classification system is a hierarchical taxonomy, just like categories. It’s unlikely your WordPress content needs as extensive an organization system.

So we know that tags and categories are taxonomies, and we know that tags are flat and categories are hierarchical. A custom taxonomy is a custom organizing system—either flat or hierarchical—that you create for your posts.

You would create additional taxonomies when you think they’ll be useful to either you or your readers. For example, we think that some of our readers may want to see only “Beginner” (like this) or more advanced content, so we created a new taxonomy called difficulty. But this doesn’t make sense on every, or even most, sites, so it’s not rolled into WordPress by default.

Other examples: if you have a travel blog, you might use a flat (tag-like) custom taxonomy called “Country,” which captures which country (or countries) you were in when you wrote each post. This way they wouldn’t be mixed into your use of WordPress’s ordinary tagging system to tag your posts with, say, “Local cuisine” and “Major landmarks,” while also letting you define, separately, whether a given post was written while you were passing through Italy and Slovenia.

A film blog might want a hierarchical (category-like) system called “Genre,” which captures that a given movie is, say, a “Comedy,” and possibly also a member of the “Romantic Comedy” subcategory. You could use this system separately from WordPress’s default “Categories,” which might capture, say, whether a given article was a “Movie Review” or just a “Detailed Plot Summary.”

In all cases, when registering a taxonomy you want to just ask yourself if it will be necessary or helpful for the sites ongoing readers and maintainers. If it’s useful to any, it’s probably worth making. But be realistic, it’s so quick to make new taxonomies in WordPress that you want to keep in mind if you (or other on-going site maintainers) will actually use them for the whole duration of the site. There isn’t a right answer, but too many taxonomies probably just amounts to a bunch of unnecessary interface clutter.

What Does WordPress Do with Its Taxonomies?

WordPress will do a series of things with its in-built taxonomies, including:

  • Create a single term listing page: WordPress will create a new page for this term. The URL of the term itself will be the name of the taxonomy followed by the name of the term. For example, if you had a ‘category’ named ‘featured’, the URL would be /category/featured. The purpose of this page is essentially to act as a listing page.
  • Create a link to the single taxonomy listing page on your individual posts: If you attach the in-built terms to your post, when you view your post on the front end, WordPress will display a clickable name of the term, generally directly under the title of the post. Clicking on the term will take you to the term listing page.
  • List your terms inside widgets: WordPress comes prebuilt with several ‘widgets’ that allow you to easily add content to your site’s widget areas (like sidebars and footers). Both your ‘categories’ and ‘tag cloud’ widgets will pull in your terms and display them as clickable links.
  • Add your terms to the navigation menu: All of your tags and categories are added to the navigation administration menu where you define and build your main menu. This allows you to easily create a link directly to your most commonly used term.

Depending on your theme, there may be be other areas that take advantage of your taxonomies.

Using a Plugin to Create a Custom Taxonomy

Just as we talked about with custom post types, you can create custom taxonomies in two basic ways: with an existing plugin, or by writing a custom plugin.

The third-party plugins that allow you to create custom post types and custom taxonomies are mostly the same as for custom post types, and work well in general.

Creating Your Custom Taxonomy with register_taxonomy()

To create a custom taxonomy with your own custom plugin, you use the WordPress function register_taxonomy, which has two required arguments:

  1. The slug name of your custom taxonomy. “Slugging” is the same process of working with text that helps make WordPress post titles into URLs. “Slugged” text looks like this: “i-am-slugged-text”. So for a taxonomy called “Movie Genre,” the “slug name” would be movie-genre.
  2. The post types that you want the taxonomy to apply to. This is also “sluggified”, so if you want the taxonomy to apply to the WordPress default post type of “Page”, you’d made the second argument 'page'.

This second argument can also be an array, which would be a list of post types. If you want a single post type to get the taxonomy, say post that’s all you need. But if you wanted both posts and pages to have it, you’d make the second argument array('post', 'page').

To make this very concrete, if your taxonomy were wanting to apply to Posts, Pages, and a new post type you made called “Awesome”, you’d use register_taxonomy() as follows:

Note that our call to register_taxonomy() is wrapped in another function, which hooks into the init action hook. If this style of function writing is new to you, please read our introduction to WordPress hooks, which is an absolutely key piece of WordPress knowledge.

How to Register Your Own Custom Taxonomy

To create your own custom taxonomies you will need to define your taxonomy using the register_taxonomy function. This function takes in three values as follows register_taxonomy($taxonomy, $object_type, $args). A brief summary of these values are detailed below:

  1. $taxonomy – Name of the new taxonomy you are creating. Where WordPress calls their taxonomy ‘categories’ or ‘tags’, you may want to give yours another name, such as ‘members’. This name has to be under 32 characters in length and may only use letters and the underscore character.
  2. $object_type – Name of the post type to which you want to attach this taxonomy. WordPress’ post post type has both categories and tags attached to it. You may want to attach your new taxonomy to an existing post type, or your own custom post type that you have previously created. You have two options in this case:
    • A single string representing the name of the post type such as $object_type = 'post'
    • An array of strings for the names of the post types such as $object_type = array('post','page')
  3. $args – These are your arguments used to set the various options for your new taxonomy. There are multiple options that you can set. Several of these are mandatory, but most are optional (WordPress will handle any missing arguments):
    • label – The plural name for your taxonomy, for example ‘members’, if you were creating a membership taxonomy.
    • labels – An array of your names and values that will be used for the taxonomy. These are used in administration areas for management. This array specifies all of the labels used for your taxonomy. If you leave this empty, WordPress will use your label value and set these. In addition, you can skip specific non-needed values and they will be defaulted.
      • name – Plural name of the taxonomy.
      • singular_name – Singular name used for one term within the taxonomy.
      • menu_name – Text to be displayed on the WordPress administration back-end (along the left hand side administration menu).
      • all_items – Viewing all terms from the taxonomy.
      • view_item – Viewing a single term from the taxonomy.
      • update_item – Updating a single taxonomy.
      • add_new_item – Add new term text.
      • parent_item – Used with hierarchal taxonomies, generally set to Parent $taxonomy_name.
      • parent_item_colon – Same as above, but also adding a colon to the end.
      • search_items – Search text used when looking through your taxonomy.
      • popular_items – Popular term name, used in the back-end administration section for non hierarchical terms. Can easily be set to Popular $taxonomy_name.
      • separate_items_with_commas – This text is displayed for non-hierarchical taxonomies, this is the text shown on the taxonomy meta box for individual posts (this is shown directly under the ‘add’ button).
      • add_or_remove_items – This text is displayed for non-hierarchical taxonomies. This text is only shown with JavaScript disabled inside the taxonomy meta box for individual pages.
      • choose_from_most_used – This text is displayed for non-hierarchical taxonomies, at the bottom of the taxonomy meta box and when selected it will show a listing of the most used terms.
      • not_found – This text is displayed for non-hierarchical taxonomies, inside the taxonomy meta box only once you have clicked on the ‘Chose From Most used’ highlighted text. Once clicked, WordPress will look for the most used terms. If there are none, this text will be displayed.
    • public – Determines if your taxonomy will be shown and be able to be queried against.
    • show_ui – Determines if WordPress will display an administration area for your taxonomy. If this is not set, you won’t have an area to manage your terms.
    • show_in_nav_menus – Determines if the terms from this taxonomy will be selectable in your navigation menu.
    • show_tagcloud – Determines if WordPress will include your taxonomy’s terms inside the tag cloud widget.
    • meta_box_cb – Lets you specify a function used to output the design of the taxonomies meta box inside your single posts. If not selected WordPress will use its default.
    • show_admin_column – This determines if your taxonomy’s terms will appear inside a new column for your post listings. Setting this to ‘true’ will display a new column for your specified post type that will display all of its attached terms.
    • hierarchical – Determines if your taxonomy can levels such as parents / children (like categories) or are all flat in level (like tags).
    • update_count_callback – Name of a function to call when there has been an update to the attached post type. When this taxonomy’s post type changes, this function will be called.
    • query_var – Determines the name used for querying the post type. By default this is set to the name of the taxonomy itself. If set to a string, that string will be used. This is best left to its default value.
    • rewrite – This can be set in multiple ways. Setting this to ‘false’ will disable permalinks. If this has not been set to false, you can specify multiple element such as the ‘slug’. This is best left to its default true value.
    • capabilities – Determines the capabilities (permissions) needed to interact with the taxonomy such as deleting, adding, assigning. This is best left to its default value.
    • sort – Specifies that when assigning terms to a post, it should remember the order.
    • _builtin – Determines if this term is a ‘built in’ taxonomy or a custom taxonomy. This should not be touched when creating your taxonomy

Remember to check the check the WordPress codex on custom taxonomies, as it outlines what values are mandatory and which are optional (along with what values are valid).

Create a tag cloud with your custom taxonomies

Let’s say you want a awesome_taxonomy cloud rather than a tag cloud. Well, we’d use our standard wp_tag_cloud() template tag with a few extra arguments. Place this code where you’d like to show your awesome_taxonomy cloud:

Customizing Taxonomy Options with $args

register_taxonomy() does accept an optional third parameter: an array of arguments, often (by convention) saved to a variable named $args.

The Codex specifies the various arguments you can pass in, but in our examples here I’m going only specify a value for two. This lets me keep my code very compact, but it can lead to some sub-optimal labels for interface buttons. This is trade-off that you have to weigh for yourself. Personally, I dislike but often honor WordPress’s need for me to write each label out for it because I like the interface to look a little more polished.

Here were only going to specify a 'label', which is the text string (like “Tag,” “Category,” or “Genre”) that names the taxonomy for users. In our example case, our label is 'Awesome Taxonomy'. We’ll also specify a true or false value for 'hierarchical'. The default is false, which makes your taxonomy “flat” or “tag-like”, but for clarity I like to specify false even if the value should just be the default.

With these two arguments specified, our final registration function for our example would look like:

A Quick Note About Taxonomy Metadata

In WordPress, taxonomies have been there almost since the beginning. But often developers found that they wanted the ability to hold and store some other data related to a taxonomy. That wasn’t really possible for a while, but now it is. This is not — by a long stretch — a common use case for taxonomies. If you’re using your taxonomy from a plugin you really don’t need to think about this feature. But because WordPress has the feature and it’s now possible, I just want to highlight it very briefly

Since WordPress 4.4 (in December 2015) you’ve been able to add metadata to taxonomy terms. A common, and likely, use case for this if if you wanted to add icons or photos to your Categories. Before term meta, there were hacks for this, but not it’s possible to use term meta itself to add this. We won’t highlight that here, but instead we’ll point you this great article on the topic from Justin Tadlock. Our core goal is to make sure you know it’s possible to store custom data on taxonomy terms, if you need it.

A handy tool for generate taxonomy is: generatewp.

Custom Fields

The third type of custom content is the custom field, also referred to as post metadata.

A custom field consists of two elements which you can see and edit in the post editing screen: the key and the value. You can use the same key again and again for multiple posts, but each will have a unique value. WordPress also gives each custom field you create its own unique ID, which means that each custom field for each post is unique even if they have the same key and value.

This is different from custom taxonomies: although you can choose from an existing key when creating a custom field, you can’t select from existing values you’ve used before. Generally this means that taxonomies are better for sorting and categorizing data.

Note: Some plugins will give you the option to choose the value of a custom field from a dropdown box, but this will use a custom metabox created by the plugin in the post editing screen, instead of the standard custom fields interface provided by WordPress.

However there are some cases in which using a custom field can be useful to sort data, for example if you want to store numerical data. In an e-commerce site you don’t want to create a taxonomy for every possible price: instead you’d insert this in a custom field. You could then use this data to allow customers to identify products with a price below $20.00 for example, or to sort by price.

You can also use custom fields to store non-numerical data, meaning you can store and display similar data between posts and display it separately from the body of the post. For example in a jobs listing site you might use custom fields to store the location, salary and working hours for a vacancy.

Displaying Custom Fields on Your Site

By default, WordPres won’t display the values you’ve entered in your custom fields unless your theme is set up to do this. You might find that your theme comes with custom field support and outputs all your custom fields on the single page for each post, but the chances are it won’t.

So you’ll need to add a template tag to do this.

A template tag is a type of function which you insert into a theme file to tell WordPress to display some data.

WordPress gives you a choice of template tags for displaying your custom fields:

  • the_meta() displays all of the custom fields for a post. You use it in the loop and it will output all custom fields’ keys and values without giving you much control.
  • get_post_meta() gives you more control. It has parameters you can use to specify which custom fields you want to get and whether you just want to retrieve one value if your post has multiple custom fields with the same key. It doesn’t actually output your custom fields though, just fetches them: to display your custom fields you have to use echo get_post_meta().
  • get_post_custom_values() lets you fetch all the values for custom fields with the same key, which you specify. Again it needs to have echo before it to output anything.

You normally add one of these to the template file in your theme which displays single posts or archives, inside the loop. Alternatively if you wanted to list custom fields for a number of posts elsewhere in the site, you could use get_post_meta() outside the loop.

For now we won’t worry about that – instead we’ll look at how you do this in the loop.

If you haven’t come across the loop before, it’s the block of code in your theme template files which fetches the title and content of each post from the database and displays it.

The first step is to open your single.php file in a code editor and find the loop. It will start with a line of code that looks something like this:

Below that you’ll find template tags such as the_title() and the_content(). You need to add your custom fields between these: I’m going to add mine immediately after the title.

Note: If you’re working with twenty fifteen, you’ll find that it doesn’t have the loop cooked in the single.php file: instead it’s in an include file called content.php. To edit the display for the product post type, create a copy of content.php, name it content-product.php, and edit that.

To display all custom fields for the post, insert this code:

Wrap up

Custom taxonomies are one of the features that really makes WordPress a fully capable CMS. Taxomonical data storage make organizing your content in sane ways so much easier. Not every WordPress site needs to have a custom plugin for new taxonomies — I’d even sat that most don’t. But when you need them, it’s great to know they’re so easy to add into a site. Organized data can be reused for years to come.

In this second part, you’ve learned how to register a custom taxonomy and display its archive pages on your site; and how to create custom fields and display those on your site too.

Do you use custom taxonomies and custom fields in your WordPress site? What do you find them mots useful for? Have your say in the comments.

About The Author

J&S Code

Sorin C is an entrepreneur, online marketer, and an employee of an IT company. When not building websites, creating content, or helping customers improve their online business, spend time with their wife and two beautiful children. Although he still feels new in WordPress, he enjoys sharing what he has learned with all of you! If you want to get in touch with him, you can do this through this website.

Put here your thoughts

Your email address will not be published. Please complete all fields * correctly You may use these HTML tags: bold text, italicised text, and paragraphs.

On the same idea

How to Remove HTML Tags from WordPress Comments
Online by stevenmedia | 8 November 2017

Nowadays, a lot of bloggers choose to remove HTML tag from WordPress websites. However, for beginners and newbies in this field, they may feel confused about the practice. Meanwhile, some...

How to create a WordPress child theme
Online by stevenmedia | 1 October 2017

The WordPress platform is a magnet for those who want to take matters into their own hands, who want complete control over their websites and want to be independent in...

Useful WordPress Hook hacks
Online by stevenmedia | 30 September 2017

Hooks are very useful in WordPress. They allow you to “hook” a custom function to an existing function, which allows you to modify WordPress’ functionality without editing core files. In...