Advertisement
  1. Code
  2. Coding Fundamentals
  3. Game Development

How to Add Custom Fields to Attachments

Scroll to top

You should be familiar with custom fields in WordPress. We use them on a post or a page to add extra data. In WordPress attachments are also saved as posts, so custom fields are available for them too.

Today we'll see how we can add some custom fields so that attachments can carry more information than just the default data.


What We'll Do

First of all, we are going to create a plugin to handle the attachments custom fields. It will get a set of options, bake them so they become part of the form when we edit an attachment, and save them into the database.

For this, we will use two WordPress hooks:


1. Create the Plugin

I will pass quickly on this part as it's not the main purpose of this tutorial.

Create a new folder in the plugins directory (wp-content/plugins/media-fields/ for example) and put a file (named plugin.php) inside. Let's also put a file called custom_media_fields.php which will hold our options.

This is what your plugin.php file should look like at first:

1
2
/*

3
Plugin Name: Wptuts+ Custom Media Fields

4
Plugin URI:

5
Description: Create attachments custom fields

6
Version: 0.1

7
Author: Guillaume Voisin

8
Author URI: https://tutsplus.com/authors/Guillaume%20Voisin

9
License: GPL2

10
*/
11
12
require_once( plugin_dir_path( __FILE__ ) . '/custom_media_fields.php' );
13
14
Class Wptuts_Custom_Media_Fields {
15
16
	private $media_fields = array();
17
18
	function __construct( $fields ) {
19
20
	}
21
22
	public function applyFilter( $form_fields, $post = null ) {
23
24
	}
25
26
	function saveFields( $post, $attachment ) {
27
28
	}
29
30
}
31
32
$cmf = new Wptuts_Custom_Media_Fields( $attchments_options );

This is the base we'll populate in the following sections. For now, let's define our set of options.


2. Define Our Options

In the other file, let's add some options to enhance the attachment edit form. We'll consider, for this tutorial, options to improve images. For instance, we'll add copyright, author description, watermark, rating, and image disposition fields.

1
2
$themename = "twentytwelve";
3
$attchments_options = array(
4
	'image_copyright' => array(
5
		'label'       => __( 'Image copyright', $themename ),
6
		'input'       => 'text',
7
		'helps'       => __( 'If your image is protected by copyrights', $themename ),
8
		'application' => 'image',
9
		'exclusions'  => array( 'audio', 'video' ),
10
		'required'    => true,
11
		'error_text'  => __( 'Copyright field required', $themename )
12
	),
13
	'image_author_desc' => array(
14
		'label'       => __( 'Image author description', $themename ),
15
		'input'       => 'textarea',
16
		'application' => 'image',
17
		'exclusions'   => array( 'audio', 'video' ),
18
	),
19
	'image_watermark' => array(
20
		'label'       => __( 'Image watermark', $themename ),
21
		'input'       => 'checkbox',
22
		'application' => 'image',
23
		'exclusions'   => array( 'audio', 'video' )
24
	),
25
	'image_stars' => array(
26
		'label'       => __( 'Image rating', $themename ),
27
		'input'       => 'radio',
28
		'options' => array(
29
			'0' => 0,
30
			'1' => 1,
31
			'2' => 2,
32
			'3' => 3,
33
			'4' => 4
34
		),
35
		'application' => 'image',
36
		'exclusions'   => array( 'audio', 'video' )
37
	),
38
	'image_disposition' => array(
39
		'label'       => __( 'Image disposition', $themename ),
40
		'input'       => 'select',
41
		'options' => array(
42
			'portrait' => __( 'portrtait', $themename ),
43
			'landscape' => __( 'landscape', $themename )
44
		),
45
		'application' => 'image',
46
		'exclusions'   => array( 'audio', 'video' )
47
	)
48
);

It is basically an associative array which contains these parameters:

  • label - the field name that will be displayed
  • input - the input type (e.g text, select, radio, ...)
  • helps - information to help the user filling in the field
  • application - which attchment mime type to apply
  • exclusions - which attchment mime type to exclude
  • required - is the field required? (default false)
  • error_text - optional field to describe the error (if required is set to true)
  • options - optional field for radio and select types
  • show_in_modal - whether to show the field in modal or not (default true)
  • show_in_edit - whether to show the field in classic edit view or not (default true)
  • extra_rows - additional rows to display content (within the same "tr" tag)
  • tr - additional rows ("tr" tag)

The highlitghted options represent options we will manually deal with whereas others are default ones WordPress will process automatically.

As we are dealing with images, we set the application parameter to "image". It will actually apply to all kinds of images whose mime type starts with "image" such as image/jpeg, image/png and so on. You could exlude the gif mime type by setting it in the exclusions field for example.

Now our options are set, let's dig into the hooks.


3. The Hooks

As mentionned earlier, we'll deal with two hooks.

We bind our two functions to those hooks in the constructor method.

1
2
function __construct( $fields ) {
3
	$this->media_fields = $fields;
4
5
	add_filter( 'attachment_fields_to_edit', array( $this, 'applyFilter' ), 11, 2 );
6
	add_filter( 'attachment_fields_to_save', array( $this, 'saveFields' ), 11, 2 );
7
}

Now let's see those hooks in detail.

attachment_fields_to_edit

It has two parameters:

  1. $form_fields - An array of fields contained in the attachment edit form
  2. $post - Object which represents the attachment itself

We will use the $form_fields parameter to merge our own fields and check each one of them against attachment requirements (mime type for instance).

1
2
public function applyFilter( $form_fields, $post = null ) {
3
	// If our fields array is not empty

4
	if ( ! empty( $this->media_fields ) ) {
5
		// We browse our set of options

6
		foreach ( $this->media_fields as $field => $values ) {
7
			// If the field matches the current attachment mime type

8
			// and is not one of the exclusions

9
			if ( preg_match( "/" . $values['application'] . "/", $post->post_mime_type) && ! in_array( $post->post_mime_type, $values['exclusions'] ) ) {
10
				// We get the already saved field meta value

11
				$meta = get_post_meta( $post->ID, '_' . $field, true );
12
13
				// Define the input type to 'text' by default

14
				$values['input'] = 'text';
15
16
				// And set it to the field before building it

17
				$values['value'] = $meta;
18
19
				// We add our field into the $form_fields array

20
				$form_fields[$field] = $values;
21
			}
22
		}
23
	}
24
25
	// We return the completed $form_fields array

26
	return $form_fields;
27
}

At this step, you should have your attachment edit form enhanced with the new fields we've added. But they will look like text inputs. We now have to consider different kinds of inputs (radio, checkbox, etc...).

So let's edit our function to handle this. Replace the $values['input'] = 'text'; with the following code:

1
2
switch ( $values['input'] ) {
3
	default:
4
	case 'text':
5
		$values['input'] = 'text';
6
		break;
7
8
	case 'textarea':
9
		$values['input'] = 'textarea';
10
		break;
11
12
	case 'select':
13
14
		// Select type doesn't exist, so we will create the html manually

15
		// For this, we have to set the input type to 'html'

16
		$values['input'] = 'html';
17
18
		// Create the select element with the right name (matches the one that wordpress creates for custom fields)

19
		$html = '<select name="attachments[' . $post->ID . '][' . $field . ']">';
20
21
		// If options array is passed

22
		if ( isset( $values['options'] ) ) {
23
			// Browse and add the options

24
			foreach ( $values['options'] as $k => $v ) {
25
				// Set the option selected or not

26
				if ( $meta == $k )
27
					$selected = ' selected="selected"';
28
				else
29
					$selected = '';
30
31
				$html .= '<option' . $selected . ' value="' . $k . '">' . $v . '</option>';
32
			}
33
		}
34
35
		$html .= '</select>';
36
37
		// Set the html content

38
		$values['html'] = $html;
39
40
		break;
41
42
	case 'checkbox':
43
44
		// Checkbox type doesn't exist either

45
		$values['input'] = 'html';
46
47
		// Set the checkbox checked or not

48
		if ( $meta == 'on' )
49
			$checked = ' checked="checked"';
50
		else
51
			$checked = '';
52
53
		$html = '<input' . $checked . ' type="checkbox" name="attachments[' . $post->ID . '][' . $field . ']" id="attachments-' . $post->ID . '-' . $field . '" />';
54
55
		$values['html'] = $html;
56
57
		break;
58
59
	case 'radio':
60
61
		// radio type doesn't exist either

62
		$values['input'] = 'html';
63
64
		$html = '';
65
66
		if ( ! empty( $values['options'] ) ) {
67
			$i = 0;
68
69
			foreach ( $values['options'] as $k => $v ) {
70
				if ( $meta == $k )
71
					$checked = ' checked="checked"';
72
				else
73
					$checked = '';
74
75
				$html .= '<input' . $checked . ' value="' . $k . '" type="radio" name="attachments[' . $post->ID . '][' . $field . ']" id="' . sanitize_key( $field . '_' . $post->ID . '_' . $i ) . '" /> <label for="' . sanitize_key( $field . '_' . $post->ID . '_' . $i ) . '">' . $v . '</label><br />';
76
				$i++;
77
			}
78
		}
79
80
		$values['html'] = $html;
81
82
		break;
83
}

Now, we can build common HTML elements. Let's check out our attachment edit form. It should look just like this:

Attachment edit form with custom fieldsAttachment edit form with custom fieldsAttachment edit form with custom fields
Attachment edit form with custom fields

The custom fields, depending on whether you set their modal options to true or not, will also appear in the media modal form when you edit a post.

Custom fields in modalCustom fields in modalCustom fields in modal
Custom fields in modal

Now our fields are displayed in our attachment edit form, we have to save them in the database. For this, we are going to use the second hook.

attachment_fields_to_save

This hook also has two parameters:

  1. $post - array which represents the attachment entity
  2. $attachment - contains all fields attached to the attachment post

Now, let's fill the function saveFields we left in the previous section.

1
2
function saveFields( $post, $attachment ) {
3
	// If our fields array is not empty

4
	if ( ! empty( $this->media_fields ) ) {
5
		// Browser those fields

6
		foreach ( $this->media_fields as $field => $values ) {
7
			// If this field has been submitted (is present in the $attachment variable)

8
			if ( isset( $attachment[$field] ) ) {
9
				// If submitted field is empty

10
				// We add errors to the post object with the "error_text" parameter we set in the options

11
				if ( strlen( trim( $attachment[$field] ) ) == 0 )
12
					$post['errors'][$field]['errors'][] = __( $values['error_text'] );
13
				// Otherwise we update the custom field

14
				else
15
					update_post_meta( $post['ID'], '_' . $field, $attachment[$field] );
16
			}
17
			// Otherwise, we delete it if it already existed

18
			else {
19
				delete_post_meta( $post['ID'], $field );
20
			}
21
		}
22
	}
23
24
	return $post;
25
}

Ok, now our custom fields are saved into the database and will be available for the front-end.

  • Please be careful when manipulating the post parameter in both hooks. It is an object in the first one and an array in the second one.
  • Tip: the update_post_meta will create the meta if it doesn't exist.
  • Tip: We prefix the custom field key with an underscore "_" so that they won't be listed in the custom fields metaboxes on post edit pages.

Error Considerations

As of version 3.5, it seems that errors still don't appear on attachment edit forms. I tried to investigate the core code, and despite the fact it should have been fixed (http://core.trac.wordpress.org/ticket/13810), it seems not.

For the ajax save process, it is certain it's not done yet as mentionned in the ajax-actions.php file:

1
2
$errors = $post['errors']; // @todo return me and display me!

So right now, errors are not going to work properly, but the code is done so that when those bugs are fixed, it'll work.


Front End

To use those custom fields in your templates, you just have to retrieve post metas the same way you would for regular posts. Don't forget to add the "_" prefix to the custom fields' keys.

For instance, you could do like so:

1
2
echo "<ul>";
3
echo "	<li><strong>Copyright</strong>: " . get_post_meta( get_the_ID(), '_image_copyright', true ) . "</li>";
4
echo "	<li><strong>Rating</strong>: " . get_post_meta( get_the_ID(), '_image_stars', true ) . "</li>";
5
echo "	<li><strong>Author description</strong>: " . get_post_meta( get_the_ID(), '_image_author_desc', true ) . "</li>";
6
echo "	<li><strong>Image disposition</strong>: " . get_post_meta( get_the_ID(), '_image_disposition', true ) . "</li>";
7
echo "	<li><strong>Watermark?</strong> " . ( get_post_meta( get_the_ID(), '_image_watermark', true ) == "on" ? "yes" : "no" ) . "</li>";
8
echo "</ul>";
Show custom fields on front-endShow custom fields on front-endShow custom fields on front-end
Show custom fields on front-end

Go Further

There are several points of improvements depending on your needs:

  • You could have your settings in the database so it becomes more flexible to add, edit, and remove them
  • You could have a default value that is set for all new attachments when a value is not set
  • You should set some style for the modal form so it displays the custom fields properly

Conclusion

Don't hesitate to share with us your ideas on how to improve this plugin and what you would expect from such functionality.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.