Using EXIF and IPTC Photo Location Information in WordPress

Reading IPTC Data

Fortunately for me, php includes the iptcparse function. This produces a complete mess of an output, with cryptic array keys containing the information. Again, the internet comes to the rescue in the shape of the IPTC Keywords Reference from phpgraphy. A slight addition to the function above, and we can now get to our lovely location information. Thanks Lightroom!

 * Fetch Geo Data from the image EXIF & IPTC data when using the wp_get_attachment_metadata() function
 * EXIF reading credit: {@author}
 * IPTC reading by {@author Gareth Cooper}
 * {@see} for IPTC keywords
function add_geo_exif($meta,$file,$sourceImageType) {
  //Read EXIF data
  $exif = @exif_read_data( $file );
  if (!empty($exif['GPSLatitude']))
    $meta['latitude'] = $exif['GPSLatitude'] ;
  if (!empty($exif['GPSLatitudeRef']))
    $meta['latitude_ref'] = trim( $exif['GPSLatitudeRef'] );
  if (!empty($exif['GPSLongitude']))
    $meta['longitude'] = $exif['GPSLongitude'] ;
  if (!empty($exif['GPSLongitudeRef']))
    $meta['longitude_ref'] = trim( $exif['GPSLongitudeRef'] );

  //Read IPTC data
  getimagesize($file, $info);
    $iptc = iptcparse($info['APP13']);

    //country name
    if (!empty($iptc['2#101'][0]))
      $meta['location']['country_name'] = trim($iptc['2#101'][0]);
    //country code
    if (!empty($iptc['2#100'][0]))
      $meta['location']['country_code'] = trim($iptc['2#101'][0]);
    //province or state
    if (!empty($iptc['2#095'][0]))
      $meta['location']['province'] = trim($iptc['2#095'][0]);
    if (!empty($iptc['2#092'][0]))
      $meta['location']['sublocation'] = trim($iptc['2#092'][0]);

  return $meta;
add_filter('wp_read_image_metadata', 'add_geo_exif','',3);

Feel free to copy and paste this into your own WordPress functions.php file. As usual, suggestions for improvements are welcome in the comments below.