Advertisement
Creative Coding

Applying Categories, Tags and Custom Taxonomies to Media Attachments

by

Have you ever been frustrated by the fact that WordPress doesn't let you assign categories or tags to your images or uploaded media?

Imagine how useful it could be: you could create dynamic galleries of images from specific places or of specific types (landscapes, abstracts etc.), or you could create listings pages for sites with a large number of PDF attachments.

The great news is that this is surprisingly easy to achieve. You can add categories and tags to your attachments with the addition of some simple code to your theme functions file or to a plugin, and you can also create a custom taxonomy that applies to attachments.

In this tutorial I'll show you how to do this, and, even better, in 10 minutes or less!

What is a Taxonomy?

According to the WordPress Codex:

Taxonomy is one of those words that most people never hear or use. Basically, a taxonomy is a way to group things together.

For example, I might have a bunch of different types of animals. I can group them together according to various characteristics and then assign those groups names. This is something most people encounter in biology classes, and it is known as the Linnaean Taxonomy.

In WordPress, a "taxonomy" is a grouping mechanism for some posts (or links or custom post types).


What You'll Need to Complete This Tutorial

You'll need:

  • A development installation of WordPress
  • Access to your theme's functions file or FTP access so you can create and upload a plugin, if you choose this method instead of editing the functions file
  • A text editor

Note: I recommend creating a plugin to add this functionality to your site, because this isn't theme-specific functionality, and you may need it if you decide to switch themes in future. Of course, adding the code to your theme's functions file will work as well.


Before Starting: The Media Editing Screen

As it stands, the Media Editing screen is pretty bare as there are no categories, tags, or taxonomies available:

attachments-and-taxonomies-media-editing-screen-before

By default, you don't have the option to select any existing categories or tags - but you can change that.


Applying Categories to Attachments

The first step is to enable categories for attachments. You do this using the register_taxonomy_for_object_type() function. In your plugin file or theme functions file, add the following:

function wptp_add_categories_to_attachments() {
	register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init' , 'wptp_add_categories_to_attachments' );

Save the file and refresh the Media Editing screen. You'll see that categories are now available:

attachments-and-taxonomies-media-editing-screen-with-categories

A column will also appear for categories in the Media Library screen, as you can see:

attachments-and-taxonomies-media-library-screen-with-categories

Note: I'm working with images here, but this will all work for all types of attachment files.


Applying Tags to Attachments

If you prefer to work with tags rather than categories (or perhaps both), you use the same function. Add the following to your functions file or plugin file:

// apply tags to attachments
function wptp_add_tags_to_attachments() {
	register_taxonomy_for_object_type( 'post_tag', 'attachment' );
}
add_action( 'init' , 'wptp_add_tags_to_attachments' );

As before, this will add tags to the Media Editing screen:

attachments-and-taxonomies-media-editing-screen-with-tags

It will also add a 'Tags' column to the Media Library screen:

attachments-and-taxonomies-media-library-screen-with-tags

Taking It Further - Creating a Custom Taxonomy for Attachments

In some cases you may not want to work with the existing categories or tags when classifying your attachments, in which case you can register a custom taxonomy and apply that to the 'attachment' post type.

In the example above I added a tag to my image to show where it was taken. Let's say I want to create a hierarchical taxonomy called 'Locations', which I can use to classify and display all of my images.

You do this using the register_taxonomy() function. In your plugin file or functions file, add the following:

// register new taxonomy which applies to attachments
function wptp_add_location_taxonomy() {
	$labels = array(
		'name'              => 'Locations',
		'singular_name'     => 'Location',
		'search_items'      => 'Search Locations',
		'all_items'         => 'All Locations',
		'parent_item'       => 'Parent Location',
		'parent_item_colon' => 'Parent Location:',
		'edit_item'         => 'Edit Location',
		'update_item'       => 'Update Location',
		'add_new_item'      => 'Add New Location',
		'new_item_name'     => 'New Location Name',
		'menu_name'         => 'Location',
	);

	$args = array(
		'labels' => $labels,
		'hierarchical' => true,
		'query_var' => 'true',
		'rewrite' => 'true',
		'show_admin_column' => 'true',
	);

	register_taxonomy( 'location', 'attachment', $args );
}
add_action( 'init', 'wptp_add_location_taxonomy' );

This creates a new, hierarchical taxonomy which can be used with attachments only.

If you wanted to apply it to other content types, you would replace the 'attachment' parameter in the register_taxonomy() function with an array containing the slugs of all the content types you wanted to include, for example:

register_taxonomy( 'location', array( 'attachment', 'post' ), $args );

The Media Editing screen now displays the new taxonomy:

attachments-and-taxonomies-media-editing-screen-with-custom-taxonomy

Because I included the 'show_admin_column' argument in my code, so does the Media Library screen:

attachments-and-taxonomies-media-library-screen-with-custom-taxonomy

And that's it! You now have categories, tags and a custom post type set up to work with media attachments.


The Summary & Uses for This Technique

As you've seen, it is possible to apply categories and tags to media attachments such as images and PDF files by using the register_taxonomy_for_object_type() function. You can also create a new taxonomy using register_taxonomy() and apply it to media attachments, either on their own or along with other content types.

Applying taxonomies (including categories and tags) to attachments in this way could have a number of practical uses:

  • Create a custom attachment.php template file to display image attachments in a gallery-style, using archive pages to display images from different categories or locations.
  • Create template files for specific taxonomies or terms to display attachments differently across the site - for example using the 'location' taxonomy, you could create a taxonomy-location-uk.php template file to display an archive of images from the UK, with location-specific styling added.
  • Categorise PDF attachments in a site with a large number of them and use archive pages to allow display of files by topic, department, media type or any other variations you need for your project.
  • In the template file for a given taxonomy, display a link to all attachments with the queried term beneath the listing of posts with that term, with direct links to the attachment files - you would use two custom queries in your template file to do this.

There are many more portential applications for this - effectively it means you can work with attachment files in the same way as you do posts and custom post types, being able to query them and display archives of them in a variety of ways.

Related Posts
  • Code
    Creative Coding
    Advanced Use of Attachments in WordPress: Creating Custom Queries for AttachmentsAdvanced use of attachments in wordpress 400
    This tutorial is the second in a four part series in which you'll learn some techniques for working with images in attachments in WordPress which give you advanced options.Read More…
  • Code
    Creative Coding
    Advanced Use of Attachments in WordPress: Assigning Categories and Taxonomy Terms to AttachmentsAdvanced use of attachments in wordpress 400
    This tutorial is the first in a four part series in which you'll learn some techniques for working with images in attachments in WordPress which give you advanced options. Read More…
  • Code
    WordPress
    Quick Tip: Post Types, Taxonomies and PermalinksPost types taxonomies urls
    Custom Post Types and taxonomies are two powerful features of WordPress. Unfortunately, they can have a tendency to cause problems if developers aren't familiar with how permalinks, URLs, and rewriting works within WordPress. In this quick tip, we aim to cover the topic very briefly to make sure you know all you need to know about WordPress URLs, custom post types, taxonomies, and how they all relate.Read More…
  • Code
    Creative Coding
    Using a Custom Post Type to Create a Home Page BannerUsing a custom post type to create a home page banner
    Sometimes it's useful to have a nice obvious banner on your site's home page—for announcements, snippets that aren't long enough to merit a blog post, or links to new content within the site. But you don't want to be editing your homepage content every time you add a new piece of content, nor do you want to be delving into the code to add content.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme from Static HTML: Creating an Archive TemplateCreating wordpress theme from html 400
    If you've been working your way through this series, you now have a functioning theme with two page templates. The steps I've demonstrated to this point are: preparing your markup for WordPress converting your HTML to PHP and splitting your file into template files editing the stylesheet and uploading your theme to WordPress adding a loop to your index file adding meta tags, the wp_head hook and the site title and description to your header file adding a navigation menu adding widget areas to the header and sidebar adding widget areas, a colophon and the wp_footer hook to the footer file creating template files for static pages. Read More…
  • Code
    Plugins
    Create a Shortcode to List Posts With Multiple ParametersPost listing shortcode main image400
    On many of the client sites I build, I find there are times when I need to include a post listing on a page. I'm not talking about archive pages here, but adding a custom listing to an existing static page. For example, I might want to list some posts on the 'About' page, or the site may require an in-depth page for a topic, with a list of posts and custom post types related to that topic. One way to do this is by creating a custom page template to include the current page content plus the results of a second custom query, but if you want more flexibility over how you list posts, or just want to do it a few times, a shortcode will be a simpler solution. In this tutorial, I'll show you how to create a simple shortcode to list all posts of a custom post type, and then I'll expand on that to create a shortcode with various parameters that users can specify to list posts however they want.Read More…