Here’s an example on how you can add custom fields to uploaded documents or other attachments within WordPress. This could be quite useful if you are displaying your attachments in a list, like we did in our previous post.
The following example will add a “Document date” field. Add this code to your functions.php file:
<?php
// Add new field to all document types, except images
function extended_meta_attachment_fields_to_edit($form_fields, $post) {
if (substr($post->post_mime_type, 0, 5) != 'image') {
$document_date = get_post_meta($post->ID, '_document_date', true);
$form_fields['document_date'] = array(
'value' => $document_date,
'label' => __('Document date'),
'helps' => __('Date when this document was published.'),
);
}
return $form_fields;
}
add_filter('attachment_fields_to_edit', 'extended_meta_attachment_fields_to_edit', 10, 2);
// Save data from the field
function extended_meta_attachment_fields_to_save($post, $attachment) {
if (isset($attachment['document_date'])) {
if (empty($attachment['document_date'])) {
delete_post_meta($post['ID'], '_document_date');
} else {
update_post_meta($post['ID'], '_document_date', $attachment['document_date']);
}
}
return $post;
}
add_filter('attachment_fields_to_save', 'extended_meta_attachment_fields_to_save', 10, 2);
?>
Custom fields for attachments can accessed using get_post_meta (same way as for posts and pages). Here’s an example where we have extended the code from our previous post with the custom field value.
<?php
$attached_documents = get_children(array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'numberposts' => -1, // show all
'post_status' => null,
'post_mime_type' => 'application/pdf,application/msword,application/vnd.ms-powerpoint,application/vnd.ms-excel,application/zip'
));
if (!empty($attached_documents)):
echo '<ul>';
foreach($attached_documents as $attached_document) {
$document_url = wp_get_attachment_url($attached_document->ID);
$document_title = apply_filters('the_title',$attached_document->post_title);
$document_date = get_post_meta($attached_document->ID, '_document_date', true);
echo '<li><a href="' . $document_url . '" title="' . $document_title . '" target="_blank">' . $document_title . '</a>, ' . $document_date . '</li>';
}
echo '</ul>';
endif;
?>