Add a Copyright Field to the Media Uploader in WordPress
by Bandicoot Marketing on | Posted in Tutorials | 13 comments
When you upload something into WordPress using the Media Uploader, you can include information such as a caption or a description. If you wanted to include something else, you would first have to create a custom field by hooking into the attachment_fields_to_edit
filter. I decided to add a “Copyright” field so that I could credit each item I upload to the original copyright owner and displayed on the front end wherever I want.
Here is the code you need to add to your functions.php file:
/** * Adding a "Copyright" field to the media uploader $form_fields array * * @param array $form_fields * @param object $post * * @return array */ function add_copyright_field_to_media_uploader( $form_fields, $post ) { $form_fields['copyright_field'] = array( 'label' => __('Copyright'), 'value' => get_post_meta( $post->ID, '_custom_copyright', true ), 'helps' => 'Set a copyright credit for the attachment' ); return $form_fields; } add_filter( 'attachment_fields_to_edit', 'add_copyright_field_to_media_uploader', null, 2 ); /** * Save our new "Copyright" field * * @param object $post * @param object $attachment * * @return array */ function add_copyright_field_to_media_uploader_save( $post, $attachment ) { if ( ! empty( $attachment['copyright_field'] ) ) update_post_meta( $post['ID'], '_custom_copyright', $attachment['copyright_field'] ); else delete_post_meta( $post['ID'], '_custom_copyright' ); return $post; } add_filter( 'attachment_fields_to_save', 'add_copyright_field_to_media_uploader_save', null, 2 ); /** * Display our new "Copyright" field * * @param int $attachment_id * * @return array */ function get_featured_image_copyright( $attachment_id = null ) { $attachment_id = ( empty( $attachment_id ) ) ? get_post_thumbnail_id() : (int) $attachment_id; if ( $attachment_id ) return get_post_meta( $attachment_id, '_custom_copyright', true ); }
With the above code in place, you can now use the following snippet to display your attachment’s new “Copyright” field within one of your page templates.
<?php echo get_featured_image_copyright(); ?>
If you leave the attachment ID parameter blank, it will display the featured image “Copyright” if your post has a featured image set.
13 comments for “Add a Copyright Field to the Media Uploader in WordPress”