I’ve got the help from a guru on other forum. The following code add fields ‘City’ and ‘Location name’ to attachment edit page. Their values gets from IPTC metadata (Tag: 90, Key: Iptc.Application2.City / Tag: 27, Key: Iptc.Application2.LocationName)
and automatically save it in db on image upload (Custom fields: ‘city
‘ and ‘locationname
‘). The values can be modified manually on the same attachment edit page.
function wp_read_image_metadata_exif( $file ) {
if ( ! file_exists( $file ) ) {
return false;
}
list( , , $image_type ) = wp_getimagesize( $file );
if ( is_callable( 'iptcparse' ) ) {
wp_getimagesize( $file, $info );
if ( ! empty( $info['APP13'] ) ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG
&& ! defined( 'WP_RUN_CORE_TESTS' )
) {
$iptc = iptcparse( $info['APP13'] );
} else {
$iptc = @iptcparse( $info['APP13'] );
}
if ( ! empty( $iptc['2#090'][0] ) ) { // City.
$meta['city'] = trim( $iptc['2#090'][0] );
}
if ( ! empty( $iptc['2#027'][0] ) ) { // Location Name.
$meta['locationname'] = trim( $iptc['2#027'][0] );
}
}
}
return apply_filters( 'wp_read_image_metadata_exif', $meta, $file, $iptc );
}
function display_exif_fields ( $form_fields, $post ){
$city = get_post_meta( $post->ID, 'city', true );
$locationname = get_post_meta( $post->ID, 'locationname', true );
$form_fields['city'] = array(
'label' => 'City',
'input' => 'text',
'value' => $city,
'helps' => '',
);
$form_fields['locationname'] = array(
'label' => 'Location name',
'input' => 'text',
'value' => $locationname,
'helps' => '',
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'display_exif_fields', 10, 2 );
function save_exif_fields( $post, $attachment ) {
$array = [ 'city', 'locationname' ];
foreach ( $array as $one ) {
if ( ! empty( $attachment[ $one ] ) ) {
update_post_meta( $post[ 'ID' ], $one, $attachment[ $one ] );
} else {
delete_post_meta( $post[ 'ID' ], $one );
}
}
return $post;
}
add_filter( 'attachment_fields_to_save', 'save_exif_fields', 10, 2 );
add_action('added_post_meta', 'save_exif_fields_on_upload', 10, 4);
function save_exif_fields_on_upload($meta_id, $post_id, $meta_key, $meta_value) {
$type = get_post_mime_type( $post_id );
$attachment_path = get_attached_file( $post_id );
$metadata = wp_read_image_metadata_exif( $attachment_path );
if($meta_key === '_wp_attachment_metadata') {
update_post_meta($post_id, 'city', $metadata['city']);
update_post_meta($post_id, 'locationname', $metadata['locationname']);
$attachment_meta = get_post_meta($post_id);
}
}