Site icon Hip-Hop Website Design and Development

How to save EXIF metadata in WordPress database?

I have a function that gets retrieves image EXIF metadata and displays it on 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 ){

$type = get_post_mime_type( $post->ID );

$attachment_path = get_attached_file( $post->ID );

$metadata = wp_read_image_metadata_exif( $attachment_path );
$form_fields['city'] = array(
    'label' => 'City',
    'input' => 'text',
    'value' => $metadata['city'],
    'helps' => '',
);

$form_fields['locationname'] = array(
    'label' => 'Location name',
    'input' => 'text',
    'value' => $metadata['locationname'],
    'helps' => '',
);

return $form_fields;
}

add_filter( 'attachment_fields_to_edit', 'display_exif_fields', 10, 2 );

The metadata displays, but I can’t handle it to save in WPDB. Following function does not bring any results:

function save_exif_fields( $post, $attachment ) {
    if( isset( $attachment['city'] ) )
        update_post_meta( $post['ID'], 'city', $attachment['city'] );

if( isset( $attachment['locationname'] ) )
    update_post_meta( $post['ID'], 'locationname', $attachment['locationname'] );

return $post;
}

add_filter( 'attachment_fields_to_save', 'save_exif_fields', 10, 2 );

What should I change it the code to solve this problem?